data is not inserting in my table - python

import MySQLdb
import csv
mydb = MySQLdb.connect(host='localhost',user='root',passwd='root', db='kabir')
cursor = mydb.cursor()
data = csv.reader(file('data.csv'))
#cursor.execute('create table actors(name varchar(20),age integer)')
for row in data:
cursor.execute('INSERT INTO actors(name,age) VALUES(%s %s)' ,row)
mydb.commit()
cursor.close()

You didn't specify a comma between %s and %s. Change it to:
cursor.execute('INSERT INTO actors(name,age) VALUES(%s, %s)' ,row)
and try..

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

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:])

Inserting an array into mysql with Python

I am building this array with 40k entries.
array = [(value1, value2, value3),(value1, value2, value3),(value1, value2, value3) .... ]
Is it possible to insert this into mysql in python something like:
cursor.execute('''INSERT IGNORE into %s VALUES *array here*''' % (table_name, array))
I am having trouble passing the array variable into mysql correctly. Any help appreciated.
Yes you can do it with executemany:
cursor.executemany('INSERT IGNORE into %s VALUES(%s, %s, %s)'%table_name, sql_data)
Note: you shouldn't use % to pass values to the database, instead you need to pass them in the second parameter of execute/executemany. i used % for the table name because the first parameter is the prepared query string.
This is Use for me try it.
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="test"
)
mycursor = mydb.cursor()
print("Insert Process... Please Wait...")
for r in range(1,tdrows+1):
a = []
for c in range(1,tdcols+1):
a.append(driver.find_element_by_xpath("//*[#id='DataTables_Table_0']/tbody/tr["+str(r)+"]/td["+str(c)+"]").text)
sql = "INSERT IGNORE into test_table(id,fname,lname) VALUES (%s, %s, %s)"
val = (a)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "Record Inserted.")

Python scraper how to add mysql insert

What is wrong in my code ? I want to add %s to my mysql db.
titlux = tree.xpath('//*[#id="offer-title"]/h1/text()')
pretx = tree.xpath('//*[#id="offer-price-stock"]/div[3]/span/#content')
print "%s," % titlux
print "%s," % pretx
print "\n"
conn = ..............
x = conn.cursor()
try:
x.execute ("""INSERT INTO produse (titlu, pret) VALUES (%s, %s)""")
conn.commit()
except:
conn.rollback()
conn.close()
You're missing the replacement variables and some quotes in your SQL insert. Change it to:
x.execute ("""INSERT INTO produse (titlu, pret) VALUES ("%s", "%s")""" % (titlux[0], pretx[0]))
#Alastair has the right answer but if you want to see the query you're using
print "INSERT INTO produse (titlu, pret) VALUES (%s, %s)" % (titlux, pretx)
x.execute ("""INSERT INTO produse (titlu, pret) VALUES (%s, %s)""" % (titlux, pretx))

Categories