So I'm running a Python script that's making some tables in my MySQL database, and I keep getting the following error:
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, "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
'0e7cc62d5339491aa701b67453405ccb (\n\t email VARCHAR(50),\n\t price' at line 1")
The thing is, it only gives the error when I try to create the table named 0e7cc62d5339491aa701b67453405ccb, other than that, the script runs fine!
Here's the code from the area that the error occurs:
def add(i, p, e):
conn = MySQLdb.connect(...)
cursor = conn.cursor()
e = str(e)
d = str(hashlib.md5(e).hexdigest())
i = str(i)
p = str(p)
q = """CREATE TABLE IF NOT EXISTS %s (
email VARCHAR(50),
price VARCHAR(15),
isbn VARCHAR(15) NOT NULL,
PRIMARY KEY (isbn))""" % (d,)
print e
print "<br />"
print i
print "<br />"
print p
print "<br />"
print "<p />"
cursor.execute(q)
q = """REPLACE INTO %s (email,price,isbn)
VALUES (%%s,%%s,%%s)""" % (d,)
cursor.execute(q, (e,p,i,))
The problem lies in the table name 0e7cc62d5339491aa701b67453405ccb starting with 0e7. Escape the table name with backticks (`) and it should work. However, as #Randy says this naming scheme is a bad idea. Unless you have very good reason, I'd seriously consider improving it.
Quoting the docs:
It is recommended that you do not use
names that begin with Me or MeN, where
M and N are integers. For example,
avoid using 1e as an identifier,
because an expression such as 1e+3 is
ambiguous. Depending on context, it
might be interpreted as the expression
1e + 3 or as the number 1e+3.
Related
I am importing the specific data from excel sheet and dumping that data to mysql database.
But while doing that i am getting the error
$ python dtz_db.py
dtz_db.py:43: Warning: Field 'datetime' doesn't have a default value
cursor.execute(query2, values2)
dtz_db.py:43: Warning: Data truncated for column 'lease_start_date' at row 1
cursor.execute(query2, values2)
dtz_db.py:43: Warning: Data truncated for column 'lease_end_date' at row 1
cursor.execute(query2, values2)
dtz_db.py:43: Warning: Incorrect integer value: '' for column 'lease' at row 1
cursor.execute(query2, values2)
dtz_db.py:43: Warning: Incorrect integer value: '' for column 'leased' at row 1
cursor.execute(query2, values2)
Traceback (most recent call last):
File "dtz_db.py", line 44, in <module>
cursor.execute(query1, values1)
File "c:\Python27\lib\site-packages\MySQLdb\cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "c:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defau
lterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.IntegrityError: (1452, 'Cannot add or update a child row: a fo
reign key constraint fails (`dtz_new`.`property_property`, CONSTRAINT `lease_id_
refs_id_816819bc` FOREIGN KEY (`lease_id`) REFERENCES `property_propertylease` (
`id`))')
my python file is this cod is for selecting the specific data from the excel file and dump that data to mysql database
import xlrd
import MySQLdb
book = xlrd.open_workbook("dtz11.xls")
sheet = book.sheet_by_name("Sheet1")
database = MySQLdb.connect (host="localhost", user="root", passwd="", db="dtz_new")
cursor = database.cursor()
query1 = """INSERT INTO property_property( name, inpection_date) VALUES(%s, %s )"""
query2 = """INSERT INTO property_propertylease( lease_start_date, lease_end_date, lease, leased) VALUES(%s, %s, %s, %s)"""
for r in range(1, sheet.nrows):
gaurav2 = sheet.cell(r,1).value
gaurav3 = sheet.cell(r,2).value
gaurav8 = sheet.cell(r,18).value
gaurav9 = sheet.cell(r,19).value
gaurav10 = sheet.cell(r,20).value
gaurav11 = sheet.cell(r,21).value
values1 = (gaurav2, gaurav3)
values2 = (gaurav8, gaurav9, gaurav10, gaurav11)
cursor.execute(query2, values2)
cursor.execute(query1, values1)
cursor.close()
database.commit()
database.close()
print "dumped successfully"
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print "I just imported "+ columns+ " columns and "+ rows+" rows to MySQL!"
and my db table schema is
Please help me to resolve this problem,,,, Thanks a lot
Your insert statement asserts that there will be 8 variables provided to the DB, but you only give it 7. Start there.
(I know neither python nor excel interaction so I haven't posted any code. I suspect the problem is entirely in that INSERT statement though.)
Edit: So the foreign key constraint error means that according to your schema, property_property's lease_id points to data in another table (property_propertylease). Since you haven't given this second table any data, the insert fails.
Put another way, your insert statement populates a parent table. The parent table is attempting to reference data in a child table that does not exist.
New to SO and fairly new to coding, so doing my best to follow the appropriate protocols.
In my python script, I'm creating a new table and populating column names from a list, named 'dups'.
dups = ['Id', 'Name', 'Price', 'Rating']
I'm inputting this list as columns for the new table, called "SuperTable", via a for loop. See code below:
with new_db:
cur = new_db.cursor()
cur.execute("DROP TABLE IF EXISTS SuperTable")
for i in dups:
if i == dups[0]:
new_col = i.replace("'","")
cur.execute("CREATE TABLE SuperTable(%s)" % (new_col))
else:
cur.execute("ALTER TABLE SuperTable ADD COLUMN %s" % i)
I've looked around a lot and can't seem to identify what I'm doing wrong. This approach worked with Sqlite but I keep getting this same error for MySQLdb:
Traceback (most recent call last):
File "MySQL_SuperTable.py", line 125, in <module>
cur.execute("CREATE TABLE Super(%s)" % (new_col))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "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 ')' at line 1")
Thanks to eggyal! He pointed out that MySQL columns require a datatype. This is what the code looks like now (I created a list of tuples to input the datatypes + column names via a for loop):
with new_db:
cur = new_db.cursor()
cur.execute("DROP TABLE IF EXISTS SuperTable")
for i in col_namestypes:
if i == col_namestypes[0]:
cur.execute("CREATE TABLE SuperTable(%s %s)" % (i))
else:
cur.execute("ALTER TABLE SuperTable ADD COLUMN %s %s" % i)
for i in new_table:
count = len(i)
question_marks = []
while a < count:
question_marks.append('%s')
a += 1
quests = ','.join(question_marks)
cur.executemany("INSERT INTO SuperTable VALUES(%s)" % quests, new_table)
I get the error when running this code:
import sqlite3
user_name = raw_input("Please enter the name: ")
user_email = raw_input("Please enter the email: ")
db = sqlite3.connect("customer")
cursor=db.cursor()
sql = """INSERT INTO customer
(name, email) VALUES (?,?);,
(user_name, user_email)"""
cursor.execute(sql)
Why is this happening?
While the other posters are correct about your statement formatting you are receiving this particular error because you are attempting to perform multiple statements in one query (notice the ; in your query which separates statements).
From Python sqlite3 docs:
"execute() will only execute a single SQL statement. If you try to execute more than one
statement with it, it will raise a Warning. Use executescript() if you want to execute
multiple SQL statements with one call."
https://docs.python.org/2/library/sqlite3.html
Now your statement will not execute properly even if you use executescript() because there are other issues with the way it is formatted (see other posted answers). But the error you are receiving is specifically because of your multiple statements. I am posting this answer for others that may have wandered here after searching for that error.
Use executescript instead of execute
execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.
https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute
You have a ;, in the middle of the query string - that is an invalid syntax. Pass a dictionary as a second argument to execute if you want to use a named parameter binding.
sql = "INSERT INTO customer (name, email) VALUES (:name, :email)"
cursor.execute(sql, {'name':user_name, 'email':user_email})
Try this:
sql = """INSERT INTO customer
(name, email) VALUES (?,?)"""
cursor.execute(sql, (user_name, user_email))
import sqlite3
def DB():
List = {"Name":"Omar", "Age":"33"}
columns = ', '.join("" + str(x).replace('/', '_') + "" for x in List.keys())
values = ', '.join("'" + str(x).replace('/', '_') + "'" for x in List.values())
sql_qry = "INSERT INTO %s ( %s ) values (?,?) ; ( %s )" % ('Table Name', columns, values)
conn = sqlite3.connect("DBname.db")
curr = conn.cursor()
# curr.execute("""create table if not exists TestTable(
# Name text,
# Age text
# )""")
# print columns
# print values
# print sql
# sql = 'INSERT INTO yell (Name , Age) values (%s, %s)'
curr.execute(sql_qry)
DB()
I am getting many warnings of the same kind --
Warning: Truncated incorrect DOUBLE value: '512121500B'
-- but cannot figure out why.
The MySQL table dr_snapshot looks like this:
PremiseID char(10) Primary Key
cycle SMALLINT(6)
last_read DATETIME
reading INTEGER
DeviceID INTEGER
I want to delete many rows by PremiseID. Here is one in particular: '512121500B'.
Here is my Python function that deletes by PremiseID:
def delDrSnapRow(premiseID, db):
sql_cmd = " ".join([
"delete ",
"from dr_snapshot ",
"where PremiseID = " + str(premiseID) + " ; "])
del_cur = db.cursor()
rc = del_cur.execute(sql_cmd)
del_cur.close()
return rc
PremiseID is a string, not a double. What am I missing here?
Many thanks.
Edit
After modifying my delete procedure to use try: .. except, I am not seeing the warning. I believe I am not seeing the warning, because I'm not seeing the warning display -- print(e) -- in the except part.
I am left with the conclusion that the try: except somehow removed the error.
def delDrSnapRow(premiseID, db):
sql_cmd = " ".join([
"delete ",
"from dr_snapshot ",
"where PremiseID = " + "'" + premiseID + "' ; "])
del_cur = db.cursor()
try:
rc = del_cur.execute(sql_cmd)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
except MySQLdb.Warning, e:
print(e)
rc = del_cur.execute(sql_cmd)
del_cur.close()
return rc
Look at this line "where PremiseID = " + str(premiseID) + " ; "])". The comparison is happening on different types and when MySQL compares different datatypes they are cast to DOUBLE internally before comparison. So you can try putting single quote around or cast around to solve the issue. So it's not try catch but the quotes which resolve the issue.
Don't roll your own query string builder, it causes all kinds of problems. Use the built in query construction syntax for your Python SQL library. If you are using MySQLdb at least, you should be able to do something like:
rc = del_cur.execute('delete from dr_snapshot where PremiseID = %s', (premiseID,))
I believe you forgot quotation marks:
sql_cmd = " ".join([
"delete ",
"from dr_snapshot ",
"where PremiseID = '" + premiseID + "' ; "])
But I strongly advise you not to execute sql statements this way, as #sr2222 explained.
I am wondering why I am receiving this error:
cmd = "INSERT INTO resulttest (category, value, timestamp) VALUES (" + key + ", " + str(value) + ", " + str(timestamp) + ")"
c.execute(cmd)
db.commit()
INSERT INTO resulttest (category, value, timestamp) VALUES (composed, 2, 1343186948.8)
Traceback (most recent call last):
File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 94, in <module>
moodParser()
File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 92, in moodParser
query()
File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 37, in query
main(columns)
File "C:/Behavioral Technology/Google Drive/twitterthingv5test.py", line 81, in main
c.execute(cmd)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
I believe it has something to do with how I am passing my values to the SQL command.
Your code to create the query isn't attempting to quote the string values:
cmd = "INSERT INTO resulttest (category, value, timestamp) VALUES (" + key + ", " + str(value) + ", " + str(timestamp) + ")"
Look at the SQL statement you printed:
INSERT INTO resulttest (category, value, timestamp) VALUES (composed, 2, 1343186948.8)
Shouldn't "category" be quoted?
You shouldn't be composing a SQL statement with string operations in the first place. This is how SQL injection vulnerabilities happen. Instead you should use placeholders and let the MySQL library deal with them:
c.execute(
"INSERT INTO resulttest (category, value, timestamp) VALUES (?, ?, ?)",
(key, value, timestamp)
)
In case Ned Batchelder's suggestion doesn't work, here's an alternative:
sql = "INSERT into resulttest (category, value, timestamp) VALUES (%s, %s, %s)"
c.execute(sql % (key, value, timestamp))
I faced a problem where my SQL command wasn't being executed, and following this kind of a syntax made it work.
Although you must be careful, because using % instead of , opens up the possibility for SQL injections, but this was the only syntax that worked for me. Might be a Python-MySQL version and compatibility problem.
A better idea would be to install compatible versions and follow the correct syntax.