Add variable value to mysql columns - python

I'm creating my first small project. I have a connection to the database using mysql-connector.
The problem is when I enter data using the input function, I create variables where I want to enter previously entered values ​​into the database.
I get an error:
*1136 (21S01): Column count doesn't match value count at row 1*
A part of code:
mycursor = db.cursor()
wartosci_do_bazy = pytanie_mysql, odpowiedz_a, odpowiedz_b, odpowiedz_c, odpowiedz_d, odpowiedz_true_mysql, value_pytanie
sql = "INSERT INTO pytania (tresc_pytania, odpowiedz_A, odpowiedz_B, odpowiedz_C, odpowiedz_D, odpowiedz_true, question_value) VALUES (wartosci_do_bazy)"
mycursor.execute(sql)
db.commit()
When I was creating a table:
mycursor.execute(
"CREATE TABLE pytania (question_id INTEGER AUTO_INCREMENT PRIMARY Key,"
"tresc_pytania VARCHAR(255), odpowiedz_A VARCHAR(255),"
"odpowiedz_B VARCHAR(255), odpowiedz_C VARCHAR(255),"
"odpowiedz_D VARCHAR(255), odpowiedz_true VARCHAR(255),"
"question_value INTEGER(255) )")

try this
mycursor = db.cursor()
#pytanie_mysql, odpowiedz_a, odpowiedz_b, odpowiedz_c, odpowiedz_d, odpowiedz_true_mysql, value_pytanie
sql = ("INSERT INTO pytania
(tresc_pytania, odpowiedz_A, odpowiedz_B, odpowiedz_C, odpowiedz_D, odpowiedz_true, question_value)
VALUES
(%s, %s, %s, %s, %s, %s, %s)",
(pytanie_mysql, odpowiedz_a, odpowiedz_b, odpowiedz_c, odpowiedz_d, odpowiedz_true_mysql, value_pytanie))
mycursor.execute(sql)
db.commit()
you can see more in this link: Using Python variables in MySQL insert statement

Thanks for help!
Solution:
wartosci_do_bazy = pytanie_mysql, odpowiedz_a, odpowiedz_b, odpowiedz_c, odpowiedz_d, odpowiedz_true_mysql, value_pytanie
print(wartosci_do_bazy)
sql = ("INSERT INTO pytania (tresc_pytania, odpowiedz_A, odpowiedz_B, odpowiedz_C, odpowiedz_D, odpowiedz_true, question_value) VALUES (%s, %s, %s, %s, %s, %s, %s)")
mycursor.execute(sql, (wartosci_do_bazy))
db.commit()

Related

I'm trying to insert values into MySQL table in Python, but I keep getting a error when I try it

I have created a table named 'Patient':
import mysql.connector as mysql
db=mysql.connect(host="localhost", user="root", password="xxxx",
database='project')
cursor = db.cursor()
pat = 'create table Patient(ID char(10) primary key,Token int(10),Name
varchar(20),Phone int(10),Email char(20),Age int(3),BG_needed
char(3),Quantity char(2),Gender char(1),Date date)'
cursor.execute(pat)
sql = 'Insert into
Patient(ID,Token,Name,Phone,Email,Age,BG_needed,Quantity,Gender)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
val = ('pat1','2','Aaron','93242995','aArons12#gmail.com','20','B-','3L','M',
'2022-10-01')
cursor.execute(sql, val)
db.commit()
for x in cursor:
print(x)
And I'm getting the output as:
DataError: Column count doesn't match value count at row 1
Can you please help me find the error?
I'm sorry if you think I'm asking a silly question, I'm just in 11th grade, and this topic wasn't taught to us. I'm trying to learn this on my own...
There are too many problems in your script. Your number of parameters don't match.
import mysql.connector as mysql
db = mysql.connect(host="localhost", user="root",
password="xxxx",database='project')
cursor = db.cursor()
pat = 'create table Patient(ID char(10) primary key,Token int(10),Name
varchar(20),Phone int(10),Email char(20),Age int(3),BG_needed
char(3),Quantity char(2),Gender char(1),Date date)'
cursor.execute(pat)
sql = 'Insert into
Patient(ID,Token,Name,Phone,Email,Age,BG_needed,Quantity,Gender,Date)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
val = ('pat1','2','Aaron','93242995','aArons12#gmail.com','20','B-
','3L','M','2022-10-01')
cursor.execute(sql, val)
db.commit()
for x in cursor:
print(x)
It was an easy fix. Hope that you find it useful

Getting InternalError: Unread result found after inserting new data

I'm new to python and MySQL but I've been trying to program a schema which has a user entity with 2 subtypes: student and instructor. When I use this function
def create_user(userName, email, Instructor):
mycursor = mydb.cursor()
generatedKey = uuid.uuid4()
id = generatedKey.bytes
generatedKey = uuid.uuid4()
PCID = generatedKey.bytes
sql = "INSERT INTO User(UserID,UserName, UserEmail) VALUES (%s, %s, %s)"
val = (id, userName, email)
mycursor.execute(sql, val)
mydb.commit()
if(Instructor):
sql = "INSERT INTO PostCreator(PCID, CreatorType) VALUES (%s, %s)"
val = (PCID, "Instructor")
mycursor.execute(sql, val)
mydb.commit()
sql = "INSERT INTO Instructor(InstructorId,PCID) VALUES (%s, %s)"
val = (id, PCID)
mycursor.execute(sql, val)
mydb.commit()
else:
sql = "INSERT INTO PostCreator(PCID, CreatorType) VALUES (%s, %s)"
val = (PCID, "Student")
mycursor.execute(sql, val)
mydb.commit()
sql = "INSERT INTO Student(StudentId,PCID) VALUES (%s, %s)"
val = (id, PCID)
mycursor.execute(sql, val)
mydb.commit()
print("Registered", userName)
to create a student I don't have any issues. However when I try to create an instructor the system either times out, or creates an instructor but and following calls on the system results in a: InternalError: Unread result found after inserting new data.
I have no idea why making a student is ok but instructors don't work. Their tables are created the same in the SQL.

Using Python to Import CSV to a MySQL table

I can not execute a Python file to import CSV file to MySQL table.
import csv
import mysql.connector
mydb = mysql.connector.connect(
host='localhost',
user='root',
passwd='',
database='ricoh_oms'
)
cursor = mydb.cursor()
csv_data = csv.reader(open("slv_internal.csv"))
for row in csv_data:
cursor.execute("INSERT INTO slv_internal (GID, FullName, CostCenter) VALUES (%s, %s, %s)")
mydb.commit()
cursor.close()
print("Done")
I am newbie and dont understand the meaning of marker %s in the error. Thansk for your help. The error is:
Error:
"mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s, %s, %s)' at
line 1"
you are trying to Execute Parameterized Query
Example:
insert_stmt = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
in code you are missing parameters:
cursor.execute("INSERT INTO slv_internal (GID, FullName, CostCenter) VALUES (%s, %s, %s)", ("value1","value2","value3"))
some documentation:
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

Is it possible to change %s to variable when importing csv to mysql?

I have this code to import my csv to mysql database:
import csv
import mysql.connector
import re
change = "hello"
mydb = mysql.connector.connect(user='root', password='',
host='localhost',
database='jeremy_db')
file = open('C:\\Users\\trendMICRO\\Desktop\\OJT\\test.csv', 'rb')
csv_data = csv.reader(file)
mycursor = mydb.cursor()
cursor = mydb.cursor()
for row in csv_data:
cursor.execute('INSERT INTO table_test(col1,col2,col3,col4)' 'VALUES(%s, %s, %s, %s)',row)
mydb.commit()
cursor.close()
print("Done")
Can I change the values of %s into my variable change = "hello"?
Please help me I'm new to python, I tried every solution but I can't find how to change the values. I tried this VALUES(hello, %s, %s, %s)',row) but it doesn't work
For this very particular case, you'd simply hardcode the value in the query:
cursor.execute('INSERT INTO ... VALUES ("hello", %s, %s, %s)', row)
Now you have only three placeholders in your query though, so you need to ensure that row is a list with three items. E.g.:
cursor.execute('INSERT INTO ... VALUES ("hello", %s, %s, %s)', row[1:])
If you really wanted to use a variable, you could do something like:
row[0] = change
cursor.execute('INSERT INTO ... VALUES (%s, %s, %s, %s)', row)
Or:
cursor.execute('INSERT INTO ... VALUES (%s, %s, %s, %s)', [change] + row[1:])

Error when inserting row to table with MySQLdb

What is wrong below?
import MySQLdb as mysql
import datetime
db = mysql.connect("localhost","root","passworld","employees" )
cursor = db.cursor()
sql = "INSERT INTO employee(id, firstname, surname, sex, employmentdate) VALUES (%s, %s, %s, %s, '%s')" %(id, firstname, surname, sex, employmentdate)
dater = datetime.datetime(2005,1,1)
cursor.execute(["012345","Mark", "Rooney", "M", dater])
OperationalError: (1054, "Unknown column 'Mark' in 'field list'")
You should pass your sql statement and params to cursor.execute():
sql = "INSERT INTO employee(id, firstname, surname, sex, employmentdate) VALUES (%s, %s, %s, %s, '%s')"
cursor.execute(sql, ["012345","Mark", "Rooney", "M", dater])
db.commit()

Categories