I tried to insert data to the database using python but I got a MySQLdb error
self.cur.execute('''
INSERT INTO book(book_name, book_desc, book_code, book_category, book_author, book_publisher, book_price)
VALUES(%s, %s, %s, %s, %s, %s, %s)
''', (book_title, book_desc, book_code, book_category, book_author, book_publisher, book_price, ))
self.db.commit()
I got this error:
MySQLdb._exceptions.OperationalError: (1366, "Incorrect integer value: '' for column 'book_code' at row 1")
According to the values you shared in the comments, book_code is a string, which is incompatible with the int value in the database. You could overcome this issue by converting it to an int:
self.cur.execute('''
INSERT INTO book(book_name, book_desc, book_code, book_category, book_author, book_publisher, book_price)
VALUES(%s, %s, %s, %s, %s, %s, %s)
''', (book_title, book_desc, int(book_code), book_category, book_author, book_publisher, book_price, ))
Related
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
So I am trying to execute this query but there is definitely a syntax error I have which I wasn't able to figure out.
If someone could help me that would be greatly appreciated. :)
query = """INSERT IGNORE INTO %s(id, title, body_text, username,time_created,num_of_comments, subreddit, full_link, upvote_ratio) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""
mycursor.execute(query, (post_table_name, tuple1),)
The current runtime error is
result = self._cmysql.convert_to_mysql(*params) _mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted
Table names and field names cannot use substitution. Assuming you're on Python 3, you can use an 'f' string:
query = f"""INSERT IGNORE INTO {post_table_name} (id, title, body_text, username,time_created,num_of_comments, subreddit, full_link, upvote_ratio) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""
mycursor.execute(query, tuple1)
I'm trying to insert many rows in MySQL database and for some reason I'm always getting this error.
I have already tried the solutions present in this topic and nothing works.
TypeError: not enough arguments for format string
My Code:
cursor = db.cursor()
row = (date, timetoserve, ipcliente, cacheCode, bytesint, method,\
url.scheme, url.hostname, url.port, url.path, auth, route[0], route[1], contentType)
items.append(row)
if Inputs % 100 == 0:
sql = "INSERT INTO LogTbl \
(DateConnection, TimeToServe, ClientIP, CacheCode, Bytes, Method,\
RequestProtocol, RequestIP, RequestPort, RequestFolder, Auth, RouteLeft, RouteRight, ContentType)\
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
cursor.executemany(sql, items)
items = []
db.commit()
I want to decode a JSON-formated string and insert it in a SQL-database via MySQL.
import json
import MySQLdb as mdb
my_json = '{"timestamp":1479132183,"sn":"B59EC63F","u":[3346,3346,3347,3346],"soc":96,"i":-32,"cc":345351,"ccMax":360000}'
parsed_stuff = json.loads(my_json)
con = None
try:
con = mdb.connect('localhost', 'name', 'password', 'mysql')
cur = con.cursor()
cur.execute("SELECT * FROM database")
cur.execute("INSERT INTO database (timestamp, sn, u0, u1, u2, u3, soc, i, cc, ccMax) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (parsed_stuff['timestamp'], parsed_stuff['sn'], parsed_stuff['u'[1]], parsed_stuff['u'[2]], parsed_stuff['u'[3]], parsed_stuff['u'[4]], parsed_stuff['soc'], parsed_stuff['i'], parsed_stuff['cc'], parsed_stuff['ccMax']))
con.commit()
except mdb.Error as e:
print("Error %d: %s" % (e.args[0], e.args[1]))
sys.exit(1)
if con:
con.close()
It throws the error:
"Unknown column 'B59EC63F' in 'field list'"
Additionally throws
"IndexError: string index out of range".
I changed
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
to
VALUES (%s, '%s', %s, %s, %s, %s, %s, %s, %s, %s)
and it works now.
I have a python script to load data to a mysql table problem that I am running into is following:
Warning: Incorrect integer value: 'user_id' for column 'user_id' at row 1
+'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',row)
Warning: Invalid TIMESTAMP value in column 'edit_time' at row 1
+'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',row)
and this is just a one line of many warning lines, I understand the error and based on my understanding I guess the row is still in the string format or the conversion didn't happen properly. I was thinking to cast each element in the row after I read them from tsv file.
example: int(row[0])
but I am not sure how to cast correctly to match MySQL timestamp type for the relevant timestamp element.
#load training data
def readtsv(file_name, con):
cur = con.cursor()
with open('file.tsv', 'rb') as f:
for row in csv.reader(f, delimiter='\t'):
cur.execute('INSERT INTO mytable(user_id, article_id, revision_id, namespace, edit_time, md5, reverted, reverted_user_id, reverted_revision_id, delta, cur_size)'
+'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',row)
try:
con.commit()
except Exception, e:
print 'unable to commit'
print e
Have you checked if your timestamp value is the correct one?
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
if it is so, MySQL will not see the error, thus no warning will exist!
As an hint simply print the insert statement string and try to launch it via "PhpMyAdmin" or other database interface tool.
The TIMESTAMP value, for MySQL is in the format: 'YYYYMMDDHHMMSS', thus today 04 Dec 2012 21:06:00 will be written in this way: '20121204210600' with quotes!