PYTHON INSERT MYSql query - python

I'm trying to execute that code in python 2.7 :
import MySQLdb, getopt
import MySQLdb.cursors
a = "TEST"
b = 1
c = 2
d = 3
e = 4
db = MySQLdb.connect(host="localhost", user="root",passwd="password",
db="database") # name of the data base
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = ""INSERT INTO `HD_coords` (`name`, `west`, `north`, `east`, `south`)
VALUES (%s, %s, %s, %s, %s)"",(a, b, c, d, e)
cur.execute(query)
cur.close()
db.commit()
So i'm getting this error :
Traceback (most recent call last):
File "MYSQL_TEST.py", line 15, in <module>
cur.execute(query)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 223, in
execute
self.errorhandler(self, TypeError, m)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in
defaulterrorhandler
raise errorvalue
TypeError: query() argument 1 must be string or read-only buffer, not tuple
nom is varchar type(255). west, north, south, east are int type.
Any clue?
Thxx

Your syntax is off. The code doing the insertion should look something like this:
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = ("INSERT INTO HD_coords (name, west, north, east, south) " +
"VALUES (%s, %s, %s, %s, %s)")
cur.execute(query, (a, b, c, d, e))
cur.close()
db.commit()
First define a SQL statement with placeholders, which you already seem to be doing. Then, bind values to those placeholders in your call to cursor.execute.

You have to put your connection object in try and expect block that can handle your connections exception
This error occurred because it's give exception before exception

You can use the .format(**locals()) which replace variable by their values:
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = "INSERT INTO HD_coords (name, west, north, east, south) VALUES ({a},{b}, {c}, {d}, {e})".format(**locals())
cur.execute(query)
cur.close()
db.commit()

Related

Syntax error of Inserting data into mysql in python 3.4 with mysql.connector

I am getting data from the web and inserting it into mysql database by the following code. There seems to be a problem in my SQL syntax for adding records in the data table. The error message goes as follows:
Can someone help with this?
Error message:
> File "D:\Clouds\Dropbox\programming\Python\get youbike info.py", line
> 33, in <module>
> cursor.execute(insert_data) File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 559,
> in execute
> self._handle_result(self._connection.cmd_query(stmt)) File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line
> 494, in cmd_query
> result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File
> "C:\Python34\lib\site-packages\mysql\connector\connection.py", line
> 396, in _handle_result
> raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1064 (42000): You have an
> error in your SQL syntax; check the manual that corresponds to your
> MariaDB server version for the right syntax to use near '%s, %s, %s,
> %s, %s, %s, %s, %s, %s)' at line 1
My Code
import urllib.request
import gzip
import json
import mysql.connector
url = "http://data.taipei/youbike"
urllib.request.urlretrieve(url,"data.gz")
f=gzip.open('data.gz','r')
jdata = f.read()
f.close()
data = json.loads(jdata.decode('utf-8'))
stationNo =1
cnx=mysql.connector.connect(user='root', host='127.0.0.1', database='bike')
cursor = cnx.cursor()
for key,value in data["retVal"].items():
sno = value["sno"]
sna = value["sna"]
sarea = value["sarea"]
lat = value["lat"]
lng = value["lng"]
ar = value["ar"]
sareaen = value["sareaen"]
snaen = value["snaen"]
aren = value["aren"]
print("NO." + sno + " " + sna)
stationNo+=1
insert_data = ("INSERT INTO info "
"(sno, sna, sarea, lat, lng, ar, sareaen, snaen, aren) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
cursor.execute(insert_data)
cnx.commit()
cursor.close()
cnx.close()
you are not passing any data to the values section, the placeholder %s are going blank as there you are not passing data
insert_data = ("INSERT INTO info "
"(sno, sna, sarea, lat, lng, ar, sareaen, snaen, aren) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
cursor.execute(insert_data,(sno, sna, sarea, lat, lng, ar, sareaen, snaen, aren))
try this
To help fault-find, do a
print "("INSERT INTO info "
"sno, sna, sarea, lat, lng, ar, sareaen, snaen, aren) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
and check the values for any double-quote marks; the presence of any will definitely cause the SQL to break.
Also, by "getting data from the web" and inserting it straight into your code as you've done opens up your app to some very serious SQL-insertion attacks, so perhaps it is best to spend some time sanitizing the web input, in addition to stripping quotation marks.

%s set correctly but PyMySQL still complaining about %d

I am new to Python and am trying to create a form that will save the data to a DB via PyMySQL, but I'm having an issue connecting to the DB. I have followed an example code (my version is below) and checked all syntax and speech marks thoroughly but am still getting the following error.
File "c:\Users\Nimrod\Nimrod Dropbox\Dropbox\Nimrodsky\Python\Adiabatic Equation\DB connect with PyMySQL.py", line 10, in <module> charset='utf8')
File "C:\ProgramData\Anaconda3\lib\site-packages\pymysql\__init__.py", line 90, in Connect return Connection(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymysql\connections.py", line 706, in __init__ self.connect()
File "C:\ProgramData\Anaconda3\lib\site-packages\pymysql\connections.py", line 922, in connect self.host_info = "socket %s:%d" % (self.host, self.port)
TypeError: %d format: a number is required, not str
import pymysql
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='sql8.freesqldatabase.com',
port='3306',
user='********',
password='**********',
db='*********',
charset='utf8')
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `client` (`ID`, `client_name`, `client_address_1`, `client_address_2`, `client_address_3`, `client_postcode`, `occupier_name`, `install_address_1`, `install_address_2`, `install_address_3`, `install_postcode`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
cursor.execute(sql, ('1', 'Terry Jones', '10 DOwning Street', 'Guildford','Surrey', 'GU1 5HA', 'Paul Smith', 'Wimbledon Hill', 'Wimbledon', 'London', 'SW19 5QT'))
#connection is not autocommit by default. So you must commit to save
#your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `occupier_name` FROM `client` WHERE `client_name`=%s"
cursor.execute(sql, ('Terry Jones',))
result = cursor.fetchone()
print (result)
finally:
connection.close
Port must be an integer: port=3306.

Python sql statement error

I've run into a problem while trying to execute an insert statement from python.
Here is my function definition:
def fill_course(param_string):
ar = param_string.split("|")
db = connect()
sql = (
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) "
"VALUES (%s, %s, %s)"
)
data = ar[0], ar[1], ar[2]
cursor = db.cursor()
cursor.execute(sql, data)
db.commit()
if cursor.rowcount == 0:
res = 0
elif cursor.rowcount == 1:
res = 1
db.close()
print(res)
return res
I've followed this link as a reference.
The error I am getting is :
File "database.py", line 25
"INSERT INTO COURSE "VALUES (%s, %s, %s)"
^
SyntaxError: invalid syntax
I am not able to understand which part of the syntax is wrong here?
Please write the following string
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) "
"VALUES (%s, %s, %s)"
like below:
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) VALUES (%s, %s, %s)"
or concatenate the two strings. As it is now, there is a syntax error.

MySQLdb: Operand should contain 1 column(s)

I am trying to insert some data into a MySQL database, using Python and MySQLdb. When I execute the following function in my program, MySQL returns error "1241, 'Operand should contain 1 column(s)'"
User, password and database are correct, the table is existing and all rights are granted.
def write_to_mysql(pname, dat, like, reachs, talker, friendsfans):
''
try:
con = mdb.connect(user='user', passwd='password', host='localhost', db='database');
except Exception. err:
print(err)
with con:
cur = con.cursor()
cur.execute("INSERT INTO fbinsights (page, datum, likes, reach, talking, fanfriends) VALUES( %s, %s, %s, %s, %s, %s)", (pname, dat, like, reachs, talker, friendsfans))
connection.commit()
Where's the mistake?
Full traceback:
File "insights.py", line 111, in <module>
main()
File "insights.py", line 108, in main
write_to_mysql(PAGE_NAME, date, likes_atm, reach_day, talking_day, friends_of_fans)
File "insights.py", line 90, in write_to_mysql
cur.execute("INSERT INTO fbinsights (page, datum, likes, reach, talking, fanfriends) VALUES( %s, %s, %s, %s, %s, %s)", (pname, dat, like, reachs, talker, friendsfans))
File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-freebsd-9.0-RELEASE-p3-amd64.egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-freebsd-9.0-RELEASE-p3-amd64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
#schlamar answered it. Wrong types passed to MySQL.
I had this error when I was generating a SELECT query with columns to select enclosed (by mistake) in parentheses: SELECT (id, name, age) FROM members;
Note that it does not raise this error if you have just one column listed in parentheses.

getting error with execute many in python

I am learning python and i am new bie.
I am trying to use functions with mysql and python and i ma getting errors
This is my script
import MySQLdb
def insert_values(cursor, values):
#cursor = self.connection.cursor()
cursor.executemany("""
insert into pythontest (name1,name2,name3)
values (%s, %s, %s)""", values)
cursor.close()
db = MySQLdb.connect("localhost","root","root","python" )
cursor = db.cursor()
var1 = ['name1','name2','name3']
insert_values(cursor,var1)
db.close()
There may be many errors because i am learning
1)i don't know how can i pass db
object in function or passing cusrsor
is ok. because i have to call that
function many times in for loop
2)is the syntax of values array ok to
go in database
ERRORS
File "mysql.py", line 10, in insert_values
values (%s, %s, %s)""", values)
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 216, in executemany
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: not enough arguments for format string
cursor.executemany("""
insert into pythontest (name1,name2,name3)
values (%s, %s, %s)""", *values)
Here's how I would write that (But untested):
import MySQLdb
def insert_values(db, values):
cursor = db.cursor()
try:
try:
cursor.execute("""
insert into pythontest (name1,name2,name3)
values (%s, %s, %s)""", *values)
except:
db.rollback()
raise
else:
db.commit()
finally:
cursor.close()
db = MySQLdb.connect("localhost","root","root","python" )
vars = ('name1','name2','name3')
insert_values(db, vars)
db.close()
The cursor starts a transaction, so you don't want to re-use the same cursor for multiple updates unless they are part of an atomic transaction.

Categories