I have an issue returning a string from my database query.
First step was to create a database:
def create_database():
# database setup
try:
con = sqlite3.connect('db/mydb.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER NOT NULL PRIMARY KEY, balance REAL NOT NULL, text TEXT NOT NULL)')
con.commit()
con.close()
except Error as e:
print('Failed to setup database.\n' + e)
exit(1)
def get_connection():
try:
con = sqlite3.connect('db/mydb.db')
return con
except:
print('Unable to connect to database. Please try again later.\n')
exit(1)
My second step was creating a user and add him with INSERT to my database:
def create_user(user_id : int):
balance = 0.0; # base unit = USD
text = create_text()
# connect to database
con = get_connection()
cur = con.cursor()
cur.execute('INSERT INTO user (id, balance, text) VALUES (?, ?, ?)', (user_id, balance, text))
database = cur.execute('SELECT * FROM user').fetchone()
print(database)
con.commit()
con.close()
def create_text():
# do some stuff which creates my text
# the text is something like 'LNURL...'
return text
This is how the result of my database query looks like:
(393120847059091456, 0.0, 'LNURL1DP68GURN8GHJ7URP09JX7MTPDCHXGEF0D3H82UNVWQHKZURF9AMRZTMVDE6HYMP0XGMQA9V7RT')
If I try to query this database for my text it returns nothing/None. My print(text) just produces an empty new line.
def get_text(user_id : int):
# connect to database
con = get_connection()
cur = con.cursor()
cur.execute('SELECT text FROM user WHERE id=?', (user_id,))
text = cur.fetchone()
con.commit()
con.close()
print(text)
return text
I think my sqlite database used 32bit int values by default. So forcing it to use 64 bit when creating the table fixed my issue:
cur.execute('CREATE TABLE IF NOT EXISTS user (id INT8 PRIMARY KEY NOT NULL, balance REAL NOT NULL, text TEXT NOT NULL')
Than I can return my result of the query with this: return text[0]
Related
I want to delete all rows in my table where the date is before or the same day as today, to update reservations in a hotel database.
dat_danas = datetime.datetime.today().date()
dat_danas.strftime("%d-%M-%Y")
conn = sqlite3.connect("rezervacije.db")
cursor = conn.cursor()
query = "DELETE FROM infoGosti WHERE DATE(odl_fld) <= ?"
cursor.execute(query, dat_danas,)
conn.commit()
Try something like this example:
import sqlite3, datetime
""" creating connection & table """
db = sqlite3.connect(':memory:') # creates db in Memory
cursor = db.cursor()
cursor.execute('''CREATE TABLE store (id INTEGER PRIMARY KEY, name TEXT, validity DATE)''')
db.commit()
""" populating data """
stores = [
['Stock 1', '12.10.2021'],
['Stock 2', '17.04.2022'],
['Stock 3', '27.11.2022'],
['Stock 4', '23.09.2022'],
]
cursor.executemany('''INSERT INTO store (name, validity) VALUES (?,?)''', stores)
db.commit()
""" queries """
today = datetime.date.today().strftime('%d.%m.%Y')
cursor.execute(""" SELECT * FROM store """) # result before deletion
db.commit()
res = cursor.fetchall()
query = """ DELETE FROM store WHERE validity < ? """
cursor.execute(query, (today,))
cursor.execute(""" SELECT * FROM store """) # result after deletion
db.commit()
res = cursor.fetchall()
I have an issue to run my SQL queries on a Postgres ElephantSql hosted:
This is my code to connect (except dynamo, user, password which are replaced by XXX
DATABASE_URL = 'postgres://YYYY:ZZZZ#drona.db.elephantsql.com:5432/YYYY'
# ---------------------------- CONNECT ELEPHANT DB
def ElephantConnect():
up.uses_netloc.append("postgres")
url = up.urlparse(DATABASE_URL)
conn = psycopg2.connect(dbname='YYYY',
user='YYYY',
password='ZZZZ',
host='drona.db.elephantsql.com',
port='5432'
)
cursor = conn.cursor()
# cursor.execute("CREATE TABLE notes(id integer primary key, body text, title text);")
#conn.commit()
# conn.close()
return conn
this code seems to connect well to db
My issue is when I want to delete a table:
def update(df, table_name, deleteYes= 'Yes'):
conn = ElephantConnect()
db = create_engine(DATABASE_URL)
cursor =conn.cursor()
if deleteYes == 'Yes': # delete
queryCount = "SELECT count(*) FROM {};".format(table_name)
queryDelete = "DELETE FROM {};".format(table_name)
count = db.execute(queryCount)
rows_before = count.fetchone()[0]
try:
db.execute(queryDelete)
logging.info('Deleted {} rows into table {}'.format(rows_before, table_name))
except:
logging.info('Deleted error into table {}'.format(table_name))
else:
pass
It seems when I run db.execute(queryDelete), it goes to the exception.
I have no message of error. But the query with count data is working...
thanks
I think that the reason for the error is because there are foreign keys against the table. In order to be sure, assign the exception into a variable and print it:
except Exception as ex:
print(ex)
By the way, if you want to quickly delete all of the rows from a table then
It will be much more efficient to truncate the table instead of deleting all the rows:
truncate table table_name
Delete is more useful when you want to delete rows under some conditions:
delete from table_name where ...
When I create the DataBase CURRENT_users.db:
import sqlite3
conn = sqlite3.connect('CURRENT_users.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
email TEXT NOT NULL,
created_in DATE NOT NULL,
password TEXT NOT NULL
)
""")
print("Success! DATABASE created with success!")
conn.close()
import UserLoginUI_Part2_Tes
t1
And I insert the DATA:
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon#Outlook.com", 2005-4-21, "Plugxyvj9");
""")
conn.commit()
print("A new user has been incremented! Now,have fun!!!")
conn.close()
import UserInterface
In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
user_INFO = cursor.execute(""" SELECT nome FROM users; """)
user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))
logged_in = False;
if user_in_SCRIPT == user_INFO:
print("You are logged in! Enjoy your new account...")
logged_in = True;
else:
print("Error: Not a valid user or USERNAME!!")
conn.close()
And it ever shows me the ELSE "command block"..
Please,who can help me?
Thanks for everything...
PRINT OF THE ERROR:
You've called SQL SELECT but you need to fetch the data.
cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()
This would return a tuple, so to get the string inside, take the zero index:
if user_in_SCRIPT == user_INFO[0]:
print("You are logged in! Enjoy your new account...")
logged_in = True
BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)
Hi I have created a database wnad when I try to insert data into it everything is added accept for the product ID. Here is the code I have.
Database creation,
import sqlite3
def create_table(db_name,table_name,sql):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",(table_name,))
result = cursor.fetchall()
keep_table = True
if len(result) == 1:
response = input("The table {0} already exists, do you want to recreate it (y/n)?: ".format(table_name))
if response == "y":
keep_table = False
print("The table {0} will be recreated - all existing data will be lost.".format(table_name))
cursor.execute("drop table if exists {0}".format(table_name))
db.commit()
else:
print("The existing table was kept")
else:
keep_table = False
if not keep_table:
cursor.execute(sql)
db.commit()
if __name__ == "__main__":
db_name = "coffee_shop.db"
sql = """create table Product
(ProductID intiger,
Name text,
Price real,
primary key(ProductID))"""
create_table(db_name, "Product", sql)
and then I was using this to insert data
import sqlite3
def insert_data(values):
with sqlite3.connect("coffee_shop.db") as db:
cursor = db.cursor()
sql = "insert into Product (Name, Price) values (?,?)"
cursor.execute(sql,values)
db.commit()
name = input("what is the product called?: ")
value = float(input("How much does it cost?: "))
if __name__ == "__main__":
product = ("{0}".format(name),"{0}".format(value))
insert_data(product)
And this is what my database ends up like, without a product id:
You gave your ProductID the type intiger; that is not a type SQLite recognizes. Correct that to be integer and the column will auto-increment.
See SQLite Autoincrement for more details.
Okay here is my code. Hopefully you can help me. I am using the MySQL lib called MySQLdb.
def createNick(self, user, nick):
try: # TRY STATEMENT HERE SO THE NICK CAN BE RECREATED
db = m.connect("host", "user", "password", "database")
cur = db.cursor()
cur.execute("CREATE TABLE nick_%s(name TEXT NOT NULL)" % user.lower())
cur.execute('INSERT INTO nick_%s(name) VALUES("%s")' % (user.lower(), nick))
db.commit()
except:
db = m.connect("host", "user", "password", "database")
cur = db.cursor()
cur.execute("DROP TABLE nick_%s" % user.lower())
cur.execute("CREATE TABLE nick_%s(name TEXT NOT NULL)" % user.lower())
cur.execute('INSERT INTO nick_%s(name) VALUES("%s")' % (user.lower(), nick))
db.commit()
def getNick(user):
db = m.connect("host", "user", "password", "database")
cur = db.cursor()
cur.execute("SELECT * FROM nick_%s" % user.lower())
nick = [nick[0] for nick in cur.fetchall()]
try: # TRY STATEMENT HERE JUST INCASE USER DID NOT MAKE ONE
return nick
except:
return user
self.createNick("username","<font color='#FFFF'>nickname</font>")
print self.getNick("username")
output: <font color=#FFF>nickname</font>
My problem is, every time I call the function it won't phrase the HTML correctly. I tried everything, can you help?
I wouldn't do that, I would use a specific data type for XML so that I save HTML to a datatype of type XML. Or I would not save HTML and insert the markup with a controller, or make my own midddleware language since it is usually not adviseable to save HTML in a database table.