Python MySQL INSERT from csv - python

I am working on a script to parse a csv file and generate input for a MySQL table.
I import the data via csv.reader, so every row is a list of strings.
I want to iterate over the rows and put different entries into the database.
I can get the following test to work:
sql = "INSERT INTO `testSmall` (`idtestSmall`, `column1`, `column2`) VALUES (1, 'entry1', 'entry2');"
cursor.execute (sql)
So my SQL connection works and the principle SQL syntax is ok.
I can also access the entries I want to put in there, and they are correct and of the data type I expect.
However, I don't seem to be able to use the same SQL syntax with variables within the iterations:
allData = csv.reader(open('TestTable.csv', 'rb'), delimiter=',', quotechar='|')
for row in allData:
sql = "INSERT INTO `testSmall` (`idtestSmall`, `column1`, `column2`) VALUES (row[0], row[1], row[2]);"
cursor.execute (sql)
This generates a Syntax Error:
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to our MySQL server version for the right syntax to use near '[0], row[1], row[2])' at line 1
But the data types are correct and the SQL syntax is the same as in the working example...
Can anyone tell me what I'm doing wrong and how to make it work?
(In the end, I want to not only insert the pure csv entries but also derived values, which is why I'm not just using mysql bulk import.)
Thanks in advance for your help!

use:
sql = "INSERT INTO `testSmall` (`idtestSmall`, `column1`, `column2`) VALUES (?, ?, ?);"
cursor.execute (sql, (row[0], row[1], row[2]))
The questionmark is a placeholder. An extra advantage of using placeholders, is that they automatically make your input 'safe', by escaping qoutes etc.
Right now, you are using the row[0], row[1], row[2] as a string with the text "row[0], row[1], row[2]", instead of telling python to use the values of these variables.
Also, if you want to use rows of multiple lengths, or if you want to be able to easily change the size of your input list, you can dynamically create the placeholders:
sql = "INSERT INTO testSmall VALUES (%s);" % ', '.join('?' for _ in row)
cursor.execute (sql, row)

The way you are doing it, row[n]s don't refer to the variable row, but they are just a piece of string sent as it is to MySQL. (I bet you come from PHP background and expect the double quotes to replace your variables with their values).
You could do this to insert the values inside the string (any string):
sql = "INSERT INTO `testSmall` (`idtestSmall`, `column1`, `column2`) VALUES (%s, %s, %s);" % row # will map each %s to the `n`th element in `row`
(this will not work, be careful, because if row[0] is abc, that string will not be enclosed in quotes, so MySQL will not interpret it as a string). Try printing the sql variable, and copy/paste it into the mysql prompt to see if it will work.
However, when used with MySQL, you better escape these, like so:
sql = "INSERT INTO `testSmall` (`idtestSmall`, `column1`, `column2`) VALUES (%s, %s, %s);"
cursor.execute(sql, row)
You can read more in the docs.

Related

Not enough arguments for format string error when inserting list into database SQL Python

I'm trying to insert a list into separate columns of a database
print inserter
params = ['%s' for item in inserter]
sql_query = 'INSERT INTO tablename (coloumn1, coloumn2, coloumn3, coloumn4, coloumn5, coloumn6, coloumn7) VALUES (%s,%s,%s,%s,%s,%s,%s);' % ','.join(params)
cursor.execute(sql_query)
db.commit
But keep getting the error
not enough arguments for format string
Anyone know what I am doing wrong?
Anyone know what I am doing wrong?
You are using string interpolation in a query.
This is bad, mainly for 2 reasons:
It is erroneous as you see. The python interpreter is confused between the %s for the interpolation and the %s for the sql parameters.
It makes your code vulnerable for sql injection.
You should use a parametrized query:
sql_query = '''INSERT INTO tablename (coloumn1, coloumn2, coloumn3,
coloumn4, coloumn5, coloumn6, coloumn7)
VALUES (%s,%s,%s,%s,%s,%s,%s);'''
cursor.execute(sql_query, inserter) # assuming inserter is a tuple/list of values

SQLite execute statement for variable-length rows

I've read the advice here about using parametrized execute call to do all the SQL escaping for you, but this seems to work only when you know the number of columns in advance.
I'm looping over CSV files, one for each table, and populating a local DB for testing purposes. Each table has different numbers of columns, so I can't simply use:
sql = "INSERT INTO TABLE_A VALUES (%s, %s)"
cursor.execute(sql, (val1, val2))
I can build up an sql statement as a string quite flexibly, but this doesn't give me the use of cursor.execute's SQL-escaping facilities, so if the input contains apostrophes or similar, it fails.
It seems like there should be a simple way to do this. Is there?
If you know the number of parameters, you can create a list of them:
count = ...
sql = "INSERT INTO ... VALUES(" + ",".join(count * ["?"]) + ")"
params = []
for i in ...:
params += ['whatever']
cursor.execute(sql, params)

dynamic table mysqldb python string/int issue

I am receiving an error when trying to write data to a database table when using a variable for the table name that I do not get when using a static name. For some reason on the line where I insert, if I insert an integer as the column values the code runs and the table is filled, however, if I try to use a string I get a SQL syntax error
cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS %s' %data[1])
sql ="""CREATE TABLE %s (IP TEXT, AVAILIBILITY INT)""" %data[1]
cursor.execute(sql)
for key in data[0]:
cur_ip = key.split(".")[3]
cursor.execute("""INSERT INTO %s VALUES (%s,%s)""" %(data[1],key,data[0][key]))
db.commit()
the problem is where I have %(data[1], key, data[0][key]) any ideas?
It's a little hard to analyse your problem when you don't post the actual error, and since we have to guess what your data actually is. But some general points as advise:
Using a dynamic table name is often not way DB-systems want to be used. Try thinking if the problem could be used by using a static table name and adding an additional key column to your table. Into that field you can put what you did now as a dynamic table name. This way the DB might be able to better optimize your queries, and your queries are less likely to get errors (no need to create extra tables on the fly for once, which is not a cheap thing to do. Also you would not have a need for dynamic DROP TABLE queries, which could be a security risk.
So my advice to solve your problem would be to actually work around it by trying to get rid of dynamic table names altogether.
Another problem you have is that you are using python string formatting and not parameters to the query itself. That is a security problem in itself (SQL-Injections), but also is the problem of your syntax error. When you use numbers, your expression evaluates to
INSERT INTO table_name VALUES (100, 200)
Which is valid SQL. But with strings you get
INSERT INTO table_name VALUES (Some Text, some more text)
which is not valid (since you have no quotes ' around the strings.
To get rid of your syntax problem and of the sql-injection-problem, don't add the values to the string, pass them as a list to execute():
cursor.execute("INSERT INTO table_name VALUES (%s,%s)", (key, data[0][key]))
If you must have a dynamic table name, put that in your query string first (e.g. with % formatting), and give the actual values for your query as parameters as above (since I cannot imagine that execute will accept the table name as a parameter).
To put it in some simple sample code. Right now you are trying to do it like this:
# don't do this, this won't even work!
table_name = 'some_table'
user_name = 'Peter Smith'
user_age = 47
query = "INSERT INTO %s VALUES (%s, %s)" % (table_name, user_name, user_age)
cursor.execute(query)
That creates query
INSERT INTO some_table VALUES (Peter Smith, 100)
Which cannot work, because of the unquoted string. So you needed to do:
# DON'T DO THIS, it's bad!
query = "INSERT INTO %s VALUES ('%s', %s)" % (table_name, user_name, user_age)
That's not a good idea, because you need to know where to put quotes and where not (which you will mess up at some point). Even worse, imagine a user named named Connor O'Neal. You would get a syntax error:
INSERT INTO some_table VALUES ('Connor O'Neal', 100)
(This is also the way sql-injections are used to crush your system / steal your data). So you would also need to take care of escaping the values that are strings. Getting more complicated.
Leave those problems to python and mysql, by passing the date (not the table name) as arguments to execute!
table_name = 'some_table'
user_name = 'Peter Smith'
user_age = 47
query = "INSERT INTO " + table_name + " VALUES (%s, %s)"
cursor.execute(query, (user_name, user_age))
This way you can even pass datetime objects directly. There are other ways to put the data than using %s, take a look at this examples http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html (that is python3 used there, I don't know which you use - but except of the print statements it should work with python2 as well, I think).

how to store a huge string (length 50000) in mysql using python

how to store a huge string (length 50000) in mysql using python.
I have a big string of length nearly 50000 .I have to store it into mysql.
Some suggested to store the string as a blob or text type.
Can anyone help me how to convert string into blob type
def main():
stringKey=''
stringValues=''
keys=ccv.keys() //ccv is a dictionary data structure
vectors=ccv.values() //ccv is a dictionary data structure
for key in keys:
stringKey='#'.join(key for key in keys)
for value in vectors:
stringValues='$'.join(str(value) for value in vectors)
insert(stringKey,stringValues)
print 'insert successful'
def insert(k,v):
db = mysql.connector.connect(user='root', password='abhi',
host='localhost',
database='cbir')
sql= 'INSERT INTO ccv(key,vector) VALUES(%s,%s)'
args = (k,v)
cursor=db.cursor()
cursor.execute(sql,args)
db.commit()
db.close()
error:
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 'key,vector) VALUES('27:1:8#27:1:9#25:2:11#6:9:8#6:9:9#6:9:6#6:9:7#6:9:4#6:9:5#27' at line 1
You made a small error in:
'INSERT INTO ccv(key,vector) VALUES(%s,%s)'
It should be:
"INSERT INTO ccv (`key`, `vector`) VALUES(%s, %s)"
Notice the ` denoting the column names.
As Larry reminded me the values don't have to be quoted for parameterized queries.
If the fields are already set for longtext this should work without needing to convert the data to blobs.
The problem was only related to the syntax and not the data or column types.
You don't need to convert the string, you need to change the field type in your database from varchar to longtext.
You are not associating the arguments with the SQL statement.
You want
cursor.execute(sql, args)
instead of
cursor.execute(sql)
sql = "INSERT INTO ccv(`key`,`vector`) VALUES(%s,%s)"
this works fine

insert json into mysql. json string is obtained from json.dumps

The problem is with inserting json strings into MySQL database.
In my python program I obtain json as a result of json.dumps(d) where d is a dictionary. Inserting code is:
query = ("INSERT INTO bm_triesJsons VALUES (%s, %s, %s);"%
(article_id, revision_number, jsn))
print query
cur.execute(query)
It looks like the problem is quotes, there is no escape symbol in front of quotes.
How can I fix this?
Use the parameterized approach to values when doing a query. The driver will handle escapes:
query = "INSERT INTO bm_triesJsons VALUES (%s, %s, %s);"
cur.execute(query, (article_id, revision_number, jsn))
If you want direct and manual access to the escape function MySQLdb uses, you can do it like this:
c = MySQLdb.connection()
print c.escape_string('{"foo":"bar"}')
# {\"foo\":\"bar\"}

Categories