I encountered error message (INVALID SYNTAX) and have no idea why it happens.
Please help to figure it out.
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxxxxxxx', db='ecommerce', charset='utf8')
ecommerce = db.cursor()
for index in range(10):
product_code = 215673140 + index +1
sql=INSERT INTO product VALUES(str(product_code),'sample data1','sample date2','sample data3'); ----> here's error point.
ecommerce.execute(sql)
db.commit()
db.close()
Try this. You have to enclose INSERT INTO ... inside " ". Also, don't use ; after the statement.
I suggest you should use %s. That way, you can insert any value inside that column
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxxxxxxx', db='ecommerce', charset='utf8')
ecommerce = db.cursor()
for index in range(10):
product_code = 215673140 + index +1
sql = "INSERT INTO product VALUES (%s, %s,%s,%s,%s)"
val = (str(product_code),'sample data1','sample date2','sample data3')
ecommerce.execute(sql, val)
db.commit()
db.close()
Related
error:
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
upi = upi_entry.get()
mysqldb = mysql.connector.connect(
host="localhost",
user="root",
password="deol9646",
database="train_login",
)
mycursor = mysqldb.cursor()
try:
mycursor.execute(
"""create table if not exists upi_data(upi text)"""
)
sql = "INSERT INTO UPI_DATA (UPI) VALUES (%s)"
val = upi
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "upi inserted successfully...")
upi_entry.delete(0, END)
upi_entry.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
The parameters need to be a tuple; you're passing in val as a single value, so the MySQL driver doesn't turn %s into anything and that ends up a syntax error.
Add a comma to make a parenthesized expression ((upi)) into a 1-tuple: (upi,)
sql = "INSERT INTO UPI_DATA (UPI) VALUES (%s)"
val = (upi,)
Hi I am trying to save a Random Number to the MySQL database. I have created a database called "RandNum1" and when I try to create the Random Number as an array I get a Type Error:"'str' object is not callable" error.
Here is what I have done so far:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="RandNum1"
)
mycursor = mydb.cursor()
import numpy as np
randnums=np.random.randint(1,20,1)
sql = "INSERT INTO RandNum (randnums) VALUES (%s)"
mycursor.execute(sql(randnums))
connection.commit()
The error is produced on this line:
mycursor.execute(sql(Randnums))
I am a newbie to Python and MySQL...any help would be appreciated.
Thanks
execute takes two arguments - the SQL string and a tuple of values:
mycursor.execute(sql, (randnums,))
Here is the code for saving the random numbers to a database (I had to abandon the Numpy part, although if anyone knows how to do that, I'd be eager to know how)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="RandNum1"
)
mycursor = mydb.cursor()
import random
randnums = random.randint(1,20)
print(randnums)
val = (randnums)
sql = "INSERT INTO RandNums (RandNum) VALUES (%s)"
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record(s) inserted.")
And here is how to print the record:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="RandNum1"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM RandNums"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Here is the corrected code:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="RandNum1"
)
mycursor = mydb.cursor()
import random
randnums = random.randint(1,20)
print(randnums)
sql = "INSERT INTO RandNums (RandNum) VALUES (%s)"
val = ("randnums")
mycursor.execute(sql,(randnums,))
mydb.commit()
print(mycursor.rowcount, "record(s) inserted.")
I have a problem getting the query results from my Python-Code. The connection to the database seems to work, but i always get the error:
"InterfaceError: No result set to fetch from."
Can somebody help me with my problem? Thank you!!!
cnx = mysql.connector.connect(
host="127.0.0.1" ,
user="root" ,
passwd="*****",
db="testdb"
)
cursor = cnx.cursor()
query = ("Select * from employee ;")
cursor.execute(query)
row = cursor.fetchall()
If your problem is still not solved, you can consider replacing the python mysql driver package and use pymysql.
You can write code like this
#!/usr/bin/python
import pymysql
db = pymysql.connect(host="localhost", # your host, usually localhost
user="test", # your username
passwd="test", # your password
db="test") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
query = ("SELECT * FROM employee")
# Use all the SQL you like
cur.execute(query)
# print all the first cell of all the rows
for row in cur.fetchall():
print(row[0])
db.close()
This should be able to find the result you want
add this to your code
for i in row:
print(i)
you did not print anything which is why that's not working
this will print each row in separate line
first try to print(row),if it fails try to execute using the for the loop,remove the semicolon in the select query statement
cursor = connection.cursor()
rows = cursor.execute('SELECT * FROM [DBname].[dbo].TableName where update_status is null ').fetchall()
for row in rows:
ds = row[0]
state = row[1]
here row[0] represent the first columnname in the database
& row[1] represent the second columnname in the database & so on
I'm trying to export a python dataframe to a SQL Server table.
Is there a better way to do this? I'm getting errors.
Dataframe - results_out
Output SQL table - FraudCheckOutput
cnn_out = pyodbc.connect('driver={SQL Server};server=XYZ;database=BulkLog;uid=sa;pwd=test')
results_out.to_sql(con=cnn_out, name='FraudCheckOutput', if_exists='replace', flavor='sqlite_master')
Thanks.
Ok, this supposed to make the work done:
import pypyodbc
def database_insert(query, params=())
conn_params = 'driver={SQL Server};server=XYZ;database=BulkLog;uid=sa;pwd=test'
try:
conn = pypyodbc.connect(conn_params)
except pypyodbc.Error, e:
print str(e)
else:
if conn.connected:
db = conn.cursor()
db.execute(query, params).commit()
finally:
if conn:
conn.close()
SQL_INSERT_QUERY = """
INSERT INTO table_name (
[field_name1],
[field_name2]
)
VALUES (
1,
'vale string'
)
WHERE
field_name3 = ?
"""
database_insert(SQL_INSERT_QUERY, ('field_name3_value',))
in pyodbc usage is very similar
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()
more on http://code.google.com/p/pyodbc/wiki/GettingStarted
I tried to fill a table in a database using MySQLdb. It did not give any errors, and once gave the warning
main.py:23: Warning: Data truncated for column 'other_id' at row 1
cur.execute("INSERT INTO map VALUES(%s,%s)",(str(info[0]).replace('\n',''), str(info[2].replace('\n','').replace("'",""))))
so I thought it was working fine. However, when it was finished and I did a row count it turned out that nothing was added. Why was the data not added to the database? The code is below
def fillDatabase():
db = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="",
db="uniprot_map")
cur = db.cursor()
conversion_file = open('idmapping.dat')
for line in conversion_file:
info = line.split('\t')
cur.execute("INSERT INTO map VALUES(%s,%s)",(str(info[0]).replace('\n',''), str(info[2].replace('\n','').replace("'",""))))
def test():
db = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="",
db="uniprot_map")
cur = db.cursor()
cur.execute("SELECT COUNT(*) FROM map")
rows = cur.fetchall()
for row in rows:
print row
def main():
fillDatabase()
test()
You need to do a db.commit() after adding all of the entries. Even if the update is not transactional, the DBAPI imposes an implicit transaction on every change.