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. :-)
Related
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]
I want to prevent duplicate usernames when people register.
Here is my code snippet:
def submit(self):
username_info = username.get()
username_password = password.get()
#connect to db
db = mysql.connector.connect(host = 'localhost', user = 'root', password = '', database = 'user')
#create a cursor
mycursor = db.cursor()
#insert to db
sql = ("INSERT INTO useraccess (user_type, password) VALUES (%s, %s)")
query = (username_info, username_password)
mycursor.execute(sql, query)
#commit
db.commit()
#create a messagebox
messagebox.showinfo("Registration", "Successfully Register")
#if username has been used
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
user_query = (username_info)
mycursor.execute(find_user, user_query)
#if (username == username_info):
if mycursor.fetchall():
messagebox.showerror("Registration", "The username chosen is already used. Please select another username")
else:
messagebox.showinfo("Registration", "Account Created!")
But every time I run it, although the username has been registered in the db, it only shows the successfully created messagebox and error:
ValueError: Could not process parameters.
Anyone can help me to solve this problem?
I believe the source of the problem is in the line
user_query = (username_info)
It should be
user_query = (username_info,)
The trailing comma is the syntactic difference between an expression in parentheses and a tuple.
Another issue with code is the query:
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
Which should be:
find_user = ("SELECT * FROM useraccess WHERE user_type = %s")
Have you checked these variables,
username_info = username.get()
username_password = password.get()
are they in proccesable formats? (i.e. can you directly put the username.get() into user_type ?)
I'm not familiar with this way of passing a parameter
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
have you double checked this? (why not the %s method?)
also, you probably get the "Account Created!" because mycursor.fetchall() fails.
I have tried 3 different variations of sqlite3 statement to SELECT a data:
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
References for these statements are from 1 2. However, none of them worked. I suspect that I am doing something really silly but can't seem to figure this out.
I want to be able to print out the data of username "monkey". Appreciate any help to point out my silly mistake.
import sqlite3
import datetime
def get_user(connection, rows='all', username=None ):
"""Function to obtain data."""
#create cursor object from sqlite connection object
cursor = connection.cursor()
if rows == 'all':
print("\nrows == 'all'")
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
for row in data:
print(row)
if rows == 'one':
print("\nrows == 'one'")
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
#cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
#cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
data = cursor.fetchone()
print('data = ',data)
cursor.close()
return data
def main():
database = ":memory:"
table = """ CREATE TABLE IF NOT EXISTS users (
created_on TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE
); """
created_on = datetime.datetime.now()
username = 'monkey'
email = 'monkey#gmail'
created_on1 = datetime.datetime.now()
username1 = 'monkey1'
email1 = 'monkey1#gmail'
# create a database connection & cursor
conn = sqlite3.connect(database)
cursor = conn.cursor()
# Insert data
if conn is not None:
# create user table
cursor.execute(table)
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on, email, username))
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on1, email1, username1))
conn.commit()
cursor.close()
else:
print("Error! cannot create the database connection.")
# Select data
alldata = get_user(conn, rows='all')
userdata = get_user(conn, rows='one', username=username )
print('\nalldata = ', alldata)
print('\nuserdata = ', userdata)
conn.close()
main()
Your table definition has the fields in order created_on, username, email but you inserted your data as created_on, email, username. Therefore the username of the first row was 'monkey#gmail'.
A good way to avoid this kind of mistake is to specify the columns in the INSERT statement rather than relying on getting the order of the original table definition correct:
INSERT INTO users (created_on, email, username) VALUES (?,?,?)
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.