error on inserting data into mysql using python - mysql

my aim was to insert name, userID and password of user so i used this code.
os.system('cls')
nme = input("enter your name: ")
usid = input("enter your userID: ")
pasd = int(input("please enter a pin in digits, characters are not supported: "))
entry = """insert into users (name, ID, pin) values('nme', 'usid', 'pasd')"""
curs.execute(entry)
but in the line5, instead of value getting inserted from variables, the whole variable is getting recognised as data input. please help!!

Related

mySQL / Python Problems

I am a new A-Level student, doing AS computer science.
I really don't know how to fix this problem but I need help with the following code.
I am trying to incorporate mySQL into Python and query data successfully. I also am trying to update a certain table via python. I am running into problems however that seem to throw errors that aren't actually happening as far as I can see. Am I blind? I hope that you geniuses can help me work it out.
The problem I have is that the SQL query I try to execute does not work and throws the following error (if the name I enter is 'Harvey', for example):
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'Harvey' in 'field list'
#Here is the actual code. It's trying to update a table record for name, DOB, and city by sorting via a unique 'key_field' identifier.
if int(key) < 1 or int(key) > len(ages):
print("The Key Field Number you entered is out of range of the data we have. Try again.")
continue
else:
n = input("""
Enter the name for the new record: """)
if len(n) > 50:
print("The name you entered is too long, try again.")
continue
c = input("""
Enter the name of the city for the new record: """)
if len(c) > 30:
print("The city you entered is too long. Try again.")
continue
dob_year = input("""
Entering the DOB (Date of Birth) for the new record...
Enter the year (YYYY): """)
if len(dob_year) != 4:
print("The year you enter must be 4 numbers long. Try again.")
continue
dob_month = input("Enter the month (MM): ")
if len(dob_month) > 2 or len(dob_month) < 1:
print("The month you enter must be 2 numbers long. Try again.")
continue
if len(dob_month) == 1:
dob_month = "0" + dob_month
dob_day = input("Enter the day (DD): ")
if len(dob_day) > 2 or len(dob_day) < 1:
print("The day you enter must be 2 numbers long. Try again.")
continue
if len(dob_day) == 1:
dob_day = "0" + dob_day
try:
int(dob_day)
int(dob_month)
int(dob_year)
except:
print("Enter integer values for the DOB (Date of Birth) section. Try again.")
continue
else:
d = "%s-%s-%s" % (dob_year, dob_month, dob_day)
ndc = []
ndc.append(n)
ndc.append(d)
ndc.append(c)
ndc = tuple(ndc)
key = int(key)
sql = "UPDATE ppl SET name = %s, dob = %s, city = %s WHERE key_field = %s" % (ndc[0], ndc[1], ndc[2], key)
mycursor.execute(sql)
mydb.commit()
You are building a string with out the proper single quotes that mysql needs t identify strings, so it takes them as colum nnames, but you should use the prepared statements that you already have
sql = "UPDATE ppl SET name = %s, dob = %s, city = %s WHERE key_field = %s"
mycursor.execute(sql,(ndc[0], ndc[1], ndc[2], key))
mydb.commit()

discord python and mysql getting specific data

I try to make a leveling system for discord with mysql and python but I can't find a way to see if user is in database, I search the internet but nothing works.
Here is the code:
#client.event
async def on_message(ctx):
author_id = str(ctx.author.id)
myresult = mycursor.execute(f"select * from level where id = {author_id}")
if myresult == author_id:
pass
else:
sqladd = "INSERT INTO level (id, level, exp) VALUES (%s, %s, %s)"
valadd = (author_id, 1, 1)
mycursor.execute(sqladd, valadd)
mydb.commit()
You need to have the bit to get values from the db setup as:
mycursor.execute(f"select * from level where id = {author_id}")
myresult = mycursor.fetchall()
Additionally, according to how your DB schema is setup, you need to specify the position of the id on the returned tuple, since you're asking for each column's value for that entry. Since you're just checking the id, I'd recommend just changing it to select id from level where id = {author_id}

Python errors occurring trying to insert data into a MySQL database table

I need to create an sql login/ sign up system for my program, however I keep hitting this error no matter what I do to change it. I need to have a randomly generated UTID, the users first and surname, along with a password that is verified, then the UserID is generated by taking the first three letters of the first name and the whole surname. I cant figure out how to overcome this.
I have tried to give the values inside the sql statement when inserting some literal datatypes, like writing "
c.execute('insert INTO tbl_Teachers (str(UTID), str(FName), str(SName), str(userPass), str(userID))VALUES(?,?,?,?,?);', var_insert) " but nothing seems to work.
def signup():
name = []
surname = []
print("Please enter the following details.")
user_type = str(input("Are you a teacher or a student: "))
if user_type == ("teacher") or ("Teacher"):
var_FName = str(input("First Name: "))
var_LName = str(input("Last Name: "))
var_password1 = str(input("Choose a password: "))
var_password2 = str(input("Please confirm password: "))
UTID = str(random.randint(0,100000))
print ("Your UserID is "+UTID+"")
name.append(var_FName)
surname.append(var_LName)
userID = []
for x in range (0, 3):
userID.append(var_FName[x])
for x in range (0,len(var_LName)):
userID.append(var_LName[x])
print (userID)
if var_password1 != var_password2:
print("Please try again.")
else:
var_insert = []
var_insert.append(UTID)
var_insert.append(var_FName)
var_insert.append(var_LName)
var_insert.append(str(var_password1))
var_insert.append(userID)
conn = sqlite3.connect('Program.db')
c = conn.cursor()
c.execute('insert INTO tbl_Teachers (UTID, FName, SName, userPass, userID)VALUES(?,?,?,?,?);', var_insert)
conn.commit()
InterfaceError: Error binding parameter 4 - probably unsupported type.
userID is supposed to be a string, but you're creating a list. Use string concatenation, not the append method.
userID = var_FName[0:3] + var_LName

showing error while adding values in to sql using variables in python code

Whenever I tried to enter new data into the database using SQL query in python it is showing error like" You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('employee').
problem is at (elif value == 2) block
import pymysql
import time
def student_database():
storage = input("Enter your database name :")
table = input("Enter your table name")
print("Press 1 for Displaying Data -->")
print("Press 2 for entering new Data..")
print("press 3 for adding new column to table..")
print("press 4 for modifying data in table")
value = int(input())
db = pymysql.connect(host='localhost', database=storage, user='', passwd='')
cursor = db.cursor()
print("Connected to " + storage)
if value == 1:
print("Printing Data :\n")
cursor.execute("SELECT * FROM (%s)" %(table))
for row in cursor:
print(row)
elif value == 2:
print("Enter New Values to be entered")
first = input("Enter First Name: ")
last = input("Enter Last Name: ")
age = input("Enter Age: ")
sex = input("Enter Sex: ")
salary = input("Enter salary amount: ")
no = input("Enter number")
# query for adding data into table
cursor.execute("INSERT INTO (%s) VALUES (%s, %s, %s, %s, %s, %s)", (table, first, last, age, sex, salary, no))
db.commit()
print("Data entered Succesfully")
elif value == 3:
print("Enter column name to be added")
column_name = input("enter new column name")
#query for adding new column in existing table
cursor.execute("Alter table employee add %s VARCHAR(10)" %column_name)
db.commit()
print("column Added successfully")
elif value == 4:
field_name = input("enter field name to be updated :")
new_value = input("Please enter your new value")
reference_name = input("enter reference column name :")
reference_value = input("enter reference value :")
cursor.execute("update employee set %s = %s WHERE %s = %s" % (field_name, new_value, reference_name, reference_value))
db.commit()
print("data modified succesfully ")
while(True):
student_database()
time.sleep(3)
if value == 2 it needs to take some inputs and enter the same data into the employee table.
You can't use placeholders for table names in prepared statements. You can only use them for data values. You should change your cursor.execute statement to:
cursor.execute("INSERT INTO "+table+" VALUES (%s, %s, %s, %s, %s, %s)", (first, last, age, sex, salary, no))
And I don't see where you give value to your table variable.

placeholders for table names in python mysql

I am using python sql to edit a very simple table named students (whose columns are name and age), as shown below:
('Rachel', 22)
('Linckle', 33)
('Bob', 45)
('Amanda', 25)
('Jacob', 85)
('Avi', 65)
('Michelle', 45)
I am defining python functions to execute SQL code.
In my first function I want to update the age values in students table where the name matches something (e.g. Bob). If I define the following function:
def update_age(age, name):
c.execute("""UPDATE students SET age = %s
WHERE name = %s""", (age, name))
And then:
update_age(99, 'Bob')
I will get:
('Rachel', 22)
('Linckle', 33)
('Bob', 99)
('Amanda', 25)
('Jacob', 85)
('Avi', 65)
('Michelle', 45)
On a second function I would like to specify also the name of the table, with the following code:
def update_age_table(table, age, name):
c.execute("""UPDATE %s SET age = %s
WHERE name = %s""",
(table, age, name)) # note that here I am only replacing students by the placeholder %s
Then if I do:
update_age_table(table='students', age=95, name='Jacob')
I will get the following error message (it is long, I am only displaying the last sentence:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''students' SET age = 95
WHERE name = 'Jacob'' at line 1
I guess that the error comes from the fact that I am assigning two of the placeholders to variables, namely age and name, which is not the case of the table name, where there is no variable assignment.
Does anyone know how I can use placeholders in SQL commands without assigning them to variables?
ThatÅ› because you cannot pass the table name as a parameter in the execute sentence. You should do it this way:
def update_age_table(table, age, name):
c.execute("UPDATE "+table+" SET age = %s
WHERE name = %s",
(table, age, name)) #
The prepared statement doesn't work for table names
EDIT
You have to remove the table parameter like this:
def update_age_table(table, age, name):
c.execute("UPDATE "+table+" SET age = %s WHERE name = %s",(age, name)) #
Sorry was a mistake
dt= datetime.datetime.now()
new_date=str(dt)
idname=input("Please enter Your Id. ")
bname= input("Please Enter name of book which you want to Issue: ")
idn=(idname,)
sql="insert into id%s (issuedbook,date)"%idn +"values (%s,%s)"
val=(bname,new_date)
cursor.execute(sql,val)
cnx.commit()
insert_data()```
Without having tested it, this should be a better coding style of the accepted answer. As the whole Q/A shows, the variables are passed only at cursor.execution() time to make it more secure, but the table statement of the execute() string is evaluated before the args are evaluated, that is why tables have to be plain text evaluated before execute() but the variables do not. See another example with similar challenge at Python - pass a list as params to SQL, plus more variables where the table is not passed either.
Therefore, just as an add-on for the rightly accepted query:
def update_age_table(UPDATE_QUERY, args):
c.execute(UPDATE_QUERY, args)
c.commit()
# example for string testing:
table, age, name = "table_x", 2, "name_y"
UPDATE_QUERY = f"""
UPDATE {table}
SET age = %s
WHERE name = %s
"""
# # UPDATE_QUERY Out:
# '\n UPDATE table_x\n SET age = %s\n WHERE name = %s\n'
args = [age, name]
update_age_table(UPDATE_QUERY, args)