Here is my code:
import mysql.connector
import datetime
import dateutil.parser
import soundfile as sf
mydb = mysql.connector.connect(
host="localhost",
user="py",
password="12345678",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (adress) VALUES (%s)"
val = ("Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
ProgrammingError Traceback (most recent call last)
in
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)' at line 1
This is due to MySQL INSERT statement syntax error. You can rewrite the query as follows:
val = "Highway 21"
sql = f'INSERT INTO customers (adress) VALUES ("{val}");'
print(sql)
# INSERT INTO customers (adress) VALUES ("Highway 21");
You have to add a , after the "Highway 21" value since val needs to be a tuple because mycursor.execute() expects a list of values:
val = ("Highway 21",)
you can also go through this code
sql = "INSERT INTO customers (adress) VALUES ('%s')"
val = ("Highway 21")
mycursor.execute(sql%(val))
val = ("Highway 21")
sql = "INSERT INTO customers (adress) VALUES ('{}') ".format(val)
print(sql)
use this you will not get error
Related
I need to install tupule value to database,but getting "Unknown column 'Mac' in 'field list'" error
Below is the code i used
import mysql.connector, csv, sys
conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="mydjangoapp",
port=3307,
)
cursor=conn.cursor()
t1=('Mac', 'Mohan')
sql="insert into books (title,isbn) values(%s,%s)" %t1
cursor.execute(sql)
Don't use % interpolation, use placeholders.
t1 = ('Mac', 'Mohan',)
cursor.execute("INSERT INTO books (title, isbn) VALUES (%s, %s)", t1)
This is not working any id why?
mysql.connector.errors.ProgrammingError: 1064 (42000): Synthax error near '%s)' at line 1
insert into a 2 fields table with a autoincrement key
I just try to insert value
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
port=3306,
user="**",
passwd="******",
database="db1"
)
mycursor = mydb.cursor()
sql = "INSERT INTO t_user (name) VALUES (%s)"
val = ('test')
mycursor.execute(sql, val)
mydb.commit()
Thank you
Statement parameters are usually passed as a tuple. If you want to make a tuple with one element, the syntax is
val = ('test',)
If you miss the comma, then val will just hold the string 'test', which won't work as your statement parameters.
I am trying to get past this error that is haunting me. I built a simple script to populate a single column database.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE IF NOT EXISTS data(pass_word VARCHAR(20))")
val = 'test'
sql = "INSERT INTO data(pass_word) VALUES '%s'"
mycursor.execute(sql, (val))
mydb.commit()
It creates the table no problem, so I know the connector is working. But it refuses to insert the val into pass_word.
It throws the following exception
Press ENTER or type command to continue
Traceback (most recent call last):
File "sql-try.py", line 19, in <module>
mycursor.execute(sql, (val))
File "/usr/local/lib/python3.6/dist-packages/mysql/connector/cursor_cext.py", line 248, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "/usr/local/lib/python3.6/dist-packages/mysql/connector/connection_cext.py", line 538, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
I think the issue was that my table only had one column, so when I was passing the val, val itself needed to be a tuple. Changing it to (sql, (val,)) did not address the issue. When I created a table with more than one column, the problem went away.
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
myname = 'jimmy'
password = 'grizwald'
mycursor.execute("CREATE TABLE IF NOT EXISTS data3(my_name VARCHAR(20), pass_word VARCHAR(20))")
val = (myname, password )
sql = "INSERT INTO data3(my_name, pass_word) VALUES (%s, %s)"
mycursor.execute(sql, val)
mydb.commit()
import MySQLdb
import datetime
water = {}
water['time'] = 1500379234.16
water['resistance'] = 18.20
water['temperature'] = 21.9
water['time'] = datetime.datetime.fromtimestamp(water['time']).strftime('%Y-%m-%d %H:%M:%S') #imports to datetime
db = MySQLdb.connect("localhost", "monitor", "password","WQMS_database")
curs = db.cursor()
curs.execute ("INSERT INTO water_data values(water['time'], water['resistance'], water['temperature'])")
Error message:
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 '['time'],
water['resistance'], water['temperature']' at line 1")
The fields in the database are datetime, float and float respectively.
water['time'] is not interpolated as you expected.
Parameterize your variables like this:
curs.execute ("INSERT INTO water_data values(%s, %s, %s)", (water['time'], water['resistance'], water['temperature']))
I am having trouble in executing this query in python. I have an IP database which has 3 column startip, endip and country. Now I want to the location of the ip. this is my code
def get_country(ip):
try:
conn = MySQLConnection(host='localhost', database='ipdb', user ='root', password='password')
cursor = conn.cursor()
query = 'SELECT * FROM db6 WHERE %s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
ip_inint= ip2int(ip)
cursor.execute(query,ip_inint)
row = cursor.fetchone()
while row is not None:
print " Start range %s end range %s country %s " %(row[0], row[1], row[2])
row = cursor.fetchone()
except Error as error:
print(error)
ip2int function is
def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]
error i am receiving is
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 BETWEEN INET_ATON(startip) AND INET_ATON(endip)' at line 1
what could be the issue?
You need to pass a tuple to execute():
cursor.execute(query, (ip_inint,))
A list will probably work too:
cursor.execute(query, [ip_inint])
An alternative is to use a dictionary with named variables in the query:
query = 'SELECT * FROM db6 WHERE %(ip_inint)s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
cursor.execute(query, {'ip_inint': ip_inint})
Reference: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html