I'm trying to insert data into sql table like this
conn = sqlite3.connect('Tags.db')
cur = conn.cursor()
input = open('word_freq_list.txt', 'r', encoding = 'UTF-8')
for word in input.read().split():
p = morph.parse(word)[0]
pos = p.tag.POS
case = p.tag.case
num = p.tag.number
gender = p.tag.gender
cur.execute(''' INSERT INTO Words_with_tags (POS, CASE, NUM, GENDER)
VALUES (?, ?, ?, ?)''', (pos, case, num, gender))
conn.commit()
But every I'm getting an error message:
sqlite3.OperationalError: near "CASE": syntax error
I can't understand why: column names are placed in the right order, the names are right too.
CASE is a Reserved Word, you can't use it as a column or variable name in your SQL query. Try using another column name instead of CASE.
I have a problem that I couldn't solve
I want to update data in a MysQl table but i get this error:
cursor.execute("UPDATE employees SET PhPath='~/Desktop/test/server/dataSet/%s' WHERE id=%s; ",(generate_names(UserID,1),UserID))
File "/home/chiheb/.virtualenvs/cv/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/home/chiheb/.virtualenvs/cv/local/lib/python2.7/site-packages/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 'User.2.1.jpg'' WHERE id=2' at line 1")
and this is a part of my code:
data = recv_msg(conn)
data = json.loads(data)
UserName = input("enter user's name: ")
UserLastName = input("enter user's last name: ")
UserPost = input("enter user's post: ")
cursor.execute("INSERT INTO employees VALUES (NULL, %s, %s, %s, %s, NULL);",(UserName, UserLastName, UserPost, data['RasID']))
db.commit()
cursor.execute("SELECT LAST_INSERT_ID(); ")
UserIDL = cursor.fetchone()
UserID = UserIDL[0]
JL= data['Jliste']
for i in range(0,10) :
cel = json.loads(JL[i])
file_name = generate_names(UserID,i+1)
img = base64.b64decode(cel['img'])
with open(file_name,'wb') as _file:
_file.write(img)
print "image {} Received ".format(i+1)
cursor.execute("UPDATE employees SET PhPath='~/Desktop/test/server/dataSet/%s' WHERE id=%s; ",(generate_names(UserID,1),UserID))
response = "images Received "
conn.send(response)
db.commit()
The problem is that you can't do partial replacement with a parameter. Generate the path in code and only use "%s" (without the quotes) as the value.
I am trying to enter data into MySQL table using MySQLdb but it is not inserting data into table.
my code is :
try:
db = MySQLdb.Connect("127.0.0.1","root","root","bank")
cursor = db.cursor()
cursor.execute("SELECT max(account_number) from pybank")
results = cursor.fetchall()
for row in results:
self.account_number = row[0]
sql = "INSERT INTO pybank(account_number,user_name, user_age, user_dob, amount) VALUES(%d,'%s',%d,'%s',%d)" %(self.account_number + 1,self.user_name, self.user_age, self.user_dob, self.total_amount)
print(sql)
cr = db.cursor()
cr.execute(sql)
db.commit()
print("Your have successfully created your account")
self.getAccountDetails()
except:
db.rollback()
print("Your account is not created !!!! ")
print
print("Please try again")
You have mistype in SQL near VALUES, also you should use placeholders:
cursor = db.cursor()
cursor.execute("INSERT INTO pybank (account_number,user_name, user_age, user_dob, amount) VALUES (%s, %s, %s, %s, %s)", (self.account_number + 1, self.user_name, self.user_age, self.user_dob, self.total_amount))
Merged with I would like some advice why this would not insert data into my SQL table.
I am receiving this error:
query() argument 1 must be string or read-only buffer, not tuple.
I am not sure what it is after trying to change my code:
def insert_popularity(Category, filename, cursor):
txt_file = file(filename, 'r')
for line in txt_file:
# Split the line on whitespace
number, value = line.split()
# construct the SQL statement
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, Category, value))
# execute the query
cursor.execute(sql)
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='dogs')
cursor = connection.cursor()
Category = 'dogs'
insert_popularity(Category, 'dogs.txt', cursor)
connection.commit()
cursor.close()
connection.close()
Following is my code:
import MySQLdb
def insert_popularity(PersonNumber, Category, Value):
# make a connection to the dataabse
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='inb104')
# get a cursor on the database
cursor = connection.cursor()
# construct the SQL statement
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, category, data))
def open_file(filename):
txt_file = file(filename, 'r')
for line in txt_file:
# Split the line on whitespace
for value in line.split():
return value
number = value[0]
data = value[1]
# execute the query
cursor.execute(sql)
# commit the changes to the database\
connection.commit()
# close the cursor and connection
cursor.close()
connection.close()
Update:
After changing my code as per Paulo's suggestion I now get this error:
query() argument 1 must be string or read-only buffer, not tuple.
I am not sure what it is after trying to change my code:
def insert_popularity(Category, filename, cursor):
txt_file = file(filename, 'r')
for line in txt_file:
# Split the line on whitespace
number, value = line.split()
# construct the SQL statement
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, Category, value))
# execute the query
cursor.execute(sql)
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='dogs')
cursor = connection.cursor()
Category = 'dogs'
insert_popularity(Category, 'dogs.txt', cursor)
connection.commit()
cursor.close()
connection.close()
Just do it simply, one thing at a time, no fancy stuff that is error prone and slows the reader down while they navigate the obfuscation:
sql = """INSERT INTO popularity (PersonNumber, Category, Value) VALUES (%s, %s, %s)"""
args = (number, Category, value)
cursor.execute(sql, args)
Your comment (execute the query) went away because (a) it was wrong (insert != query) and (b) the fixed version (execute the insertion) would be quite redundant given the clarity of the fixed code.
Update after new problem (too many values to unpack):
Instead of this code:
for line in txt_file:
# Split the line on whitespace
number, value = line.split()
do this:
for lino, line in enumerate(txt_file, 1):
pieces = line.split()
if len(pieces) != 2:
print "Bad data in line %d: %r" % (lino, pieces)
continue
number, value = pieces
You've created the query to execute as a tuple. There two possibilities to solve this:
Use the created query (sql) as a list of arguments:
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, Category, value))
# execute the query
cursor.execute(*sql)
Directly add the query to the execute method:
cursor.execute("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, Category, value))
Number 2 is definitely a better option than the first one. Thanks to all comments!
What are the data types of the number, category, and data? If any of these are strings, then you should wrap them in single quotes in your query.
Do not take me wrong, but the code is very messed up...
the return inside the for loop will return the first splited string in the first line.
open_file is defined but never called
and so on...
My take would be something like:
def process_file(category, filename, cursor):
txt_file = file(filename, 'r')
for line in txt_file:
number, value = line.split()
sql = ("""INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)""", (number, category, data))
cursor.execute(sql)
connection = MySQLdb.connect(host='localhost', user='root',
passwd='password', db='inb104')
# get a cursor on the database
cursor = connection.cursor()
category = 'foo'
process_file(category, 'somefile.txt', cursor)
# commit the changes to the database\
connection.commit()
# close the cursor and connection
cursor.close()
connection.close()
Try it like this:
def insert_popularity(Category, filename, cursor):
sql = """INSERT INTO popularity (PersonNumber, Category, Value)
VALUES(%s, %s, %s)"""
txt_file = file(filename, 'r')
for line in txt_file:
# Split the line on whitespace
number, value = line.split()
# execute the query
cursor.execute(sql, (number, Category, value))
txt_file.close()
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='dogs')
cursor = connection.cursor()
Category = 'dogs'
insert_popularity(Category, 'dogs.txt', cursor)
connection.commit()
cursor.close()
connection.close()
Also note: your code suggests this is a MySQL database; if it's an SQLite database, like the title of your question says, please substitute '?' for every '%s' in the sql statement.