python cannot insert string in table - python

I did a coding for dynamic updating table. it gave me output,but i can only insert Integers not strings it gives me "operational error" if i enter strings,I tried altering the table field datatype, but still it accepts integers only,I think it needs a change within the program.Please help:
Here's my code:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter title: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
a=data()
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
cursor.execute(query)
db.commit()
db.close()
what should i change so that it accepts both integers and strings as input?please help
error :
Enter film: 123
Enter title: adarsh
Enter year: 1234
Enter director: 132
**error**
Traceback (most recent call last):
File "C:\Python27\maybe1.py", line 22, in <module>
cursor.execute(query)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'adarsh' in 'field list'")
Datatypes:
file123 int(11),title_ varchar(50),year int(11),director varchar(12)

i think you need to add '%s' for the string and %s to the integers
query = "INSERT INTO films (file123, title_, year, director) VALUES ('%s', '%s', %s, '%s')" % (a.file123, a.title_, a.year, a.director)
or
query = "INSERT INTO films (file123, title_, year, director) VALUES (?,?,?,?)"
curs.excute(query,[a.file123, a.title_, a.year, a.director])
Explanation what wrong with your code:
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter title: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
raw_input("Enter film: ") always a string . so you need to convert each variable to appropriate type eg :file123 to int; year to int
now
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
print query
it gives
INSERT INTO films (file123, title_, year, director) VALUES (123, adars, 200, sundar)
but right format should be
INSERT INTO films (file123, title_, year, director) VALUES (123, 'adars', 200, 'sundar')
this happens due to %s directly put values as string without quotes so instead of %s use ?

I think this is better:
cursor.execute("INSERT INTO films (file123, title_, year, director) "
"VALUES (%s, %s, %s, %s)",
(a.file123, a.title_, a.year, a.director))
Just let MySQLdb do the variables formatting job for you, you do not need to add quotes yourself and it's more safe.
Here are examples.

Related

I'm trying to insert values into MySQL table in Python, but I keep getting a error when I try it

I have created a table named 'Patient':
import mysql.connector as mysql
db=mysql.connect(host="localhost", user="root", password="xxxx",
database='project')
cursor = db.cursor()
pat = 'create table Patient(ID char(10) primary key,Token int(10),Name
varchar(20),Phone int(10),Email char(20),Age int(3),BG_needed
char(3),Quantity char(2),Gender char(1),Date date)'
cursor.execute(pat)
sql = 'Insert into
Patient(ID,Token,Name,Phone,Email,Age,BG_needed,Quantity,Gender)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
val = ('pat1','2','Aaron','93242995','aArons12#gmail.com','20','B-','3L','M',
'2022-10-01')
cursor.execute(sql, val)
db.commit()
for x in cursor:
print(x)
And I'm getting the output as:
DataError: Column count doesn't match value count at row 1
Can you please help me find the error?
I'm sorry if you think I'm asking a silly question, I'm just in 11th grade, and this topic wasn't taught to us. I'm trying to learn this on my own...
There are too many problems in your script. Your number of parameters don't match.
import mysql.connector as mysql
db = mysql.connect(host="localhost", user="root",
password="xxxx",database='project')
cursor = db.cursor()
pat = 'create table Patient(ID char(10) primary key,Token int(10),Name
varchar(20),Phone int(10),Email char(20),Age int(3),BG_needed
char(3),Quantity char(2),Gender char(1),Date date)'
cursor.execute(pat)
sql = 'Insert into
Patient(ID,Token,Name,Phone,Email,Age,BG_needed,Quantity,Gender,Date)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
val = ('pat1','2','Aaron','93242995','aArons12#gmail.com','20','B-
','3L','M','2022-10-01')
cursor.execute(sql, val)
db.commit()
for x in cursor:
print(x)
It was an easy fix. Hope that you find it useful

python sqlite3 insert table error: cursor is not connected?

I try to use sqlite3 to import data to a table babyName in my AWS RDS database. For the two methods I tried, the first one data_entry() works fine every time but the second new_data_entry() gave me
Cursor is not connected
or
Not all parameters are used
error. Could you please help me?
import mysql.connector
from mysql.connector import errorcode
# start connection
try:
cnn = mysql.connector.connect(
user = '*****',
password = '*****',
host = '*****-mysql.*****.us-****-1.rds.amazonaws.com',
database = '*******')
print('It works!')
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
# start cursor
import sqlite3
c = cnn.cursor()
def creat_table():
c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
cnn.commit()
c.close()
cnn.close()
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
cnn.commit()
c.close()
cnn.close()
# creat_table()
data_entry()
print('It works!')
new_data_entry()
The error message I kept getting:
It works!
It works!
Traceback (most recent call last):
File "/Users/*****/sqlite3_python_cc.py", line 53, in <module>
new_data_entry()
File "/Users/*****/sqlite3_python_cc.py", line 45, in new_data_entry
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", values)
File "/Users/*****/anaconda/lib/python3.6/site-packages/mysql/connector/cursor.py", line 529, in execute
raise errors.ProgrammingError("Cursor is not connected")
mysql.connector.errors.ProgrammingError: Cursor is not connected
At the end of data_entry you have closed the connection to the database, cnn, which is saved as a variable in the global scope. When you attempt to run new_data_entry, the connection has already been closed, which is what is give you the error.
Instead, leave the connection open until you are finished.
import sqlite3
c = cnn.cursor()
def creat_table():
c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
cnn.commit()
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
cnn.commit()
def finish():
c.close()
cnn.close()
data_entry()
print('It works!')
new_data_entry()
finish()
I have the problem solved!
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (%s, %s, %s, %s)", (name, gender, frequency, year))
cnn.commit()
def finish():
c.close()
cnn.close()
Change all the "?" to "%s" and the codes all run through~ Thank you guys!

SQL syntax error with python

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.

TypeError: not all arguments converted during string formatting

I have a python webscraping code which runs very well if I dont insert any result in the database. i.e when i comment out this part of the code
"""
Connecting to Database and putting data into in
"""
db= MySQLdb.connect("localhost","XXX","XXX","hmm_Raw_Data")
cursor=db.cursor()
#checking phase to stop scraping
sql = """SELECT Short_link FROM RentalWanted WHERE Short_link=%s"""
rows = cursor.execute(sql,(link_result))
if rows>=1:
duplicate_count+=1
print duplicate_count
# if duplicate_count>=15:
# print "The program has started getting duplicates now- The program is terminating"
# sys.exit()
else:
query="""INSERT INTO RentalWanted
(Sale_Rent,
Type,
Area,
Nearby,
Title,
Price,
PricePerSqrFt,
Bedroom,
Agency_Fee,
Bathroom,
Size,
ZonedFor,
Freehold,
Prop_ref,
Furnished_status,
Rent_payment,
Building_info,
Amenities,
Trade_name,
Licence,
RERA_ID,
Phone_info,
Short_link)
values(
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s,
%s)"""
cursor.execute(query,(
Sale_Rent_result,
Type_result,
area_result,
nearby_result,
title_result,
price_result,
Pricepersq_result,
bedroom_result,
agencyfee_result,
bathroom_result,
size_result,
Zoned_for_result,
Freehold_result,
propertyref_result,
furnished_result,
rent_is_paid_result,
building_result,
Amenities_result,
tradename_result,
licencenum_result,
reraid_result,
phone_result,
link_result))
db.commit()
cursor.close()
db.close()
The error I get when putting the above code is this:
Traceback (most recent call last): File "RentalWanted.py", line 461, in <module>
getting_urls_of_all_pages() File "RentalWanted.py", line 45, in getting_urls_of_all_pages
every_property_in_a_page_data_extraction(a['href']) File "RentalWanted.py", line 365, in every_property_in_a_page_data_extraction
rows = cursor.execute(sql,(link_result)) File "/usr/lib/python2.6/site-packages/MySQL_python-1.2.5-py2.6-linux-x86_64.egg/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args]) TypeError: not all arguments converted during string formatting
I think there is something wrong with the query I am making.
Can anyone help me with figuring out which part needs to be fixed. I have spent hours but have no idea where I am wrong
Thanks
Do you really have 23 seperate variables? Better put all into one dictionary, so that it's clearer, what belongs together, and you don't have to count so much. The error is, that execute expects a list as last argument, and link_result is probably a string with more than one character, e.g. a list with more than one element:
result = {
"Sale_Rent": Sale_Rent_result,
"Type": Type_result,
"Area": area_result,
"Nearby": nearby_result,
"Title": title_result,
"Price": price_result,
"PricePerSqrFt": Pricepersq_result,
"Bedroom": bedroom_result,
"Agency_Fee": agencyfee_result,
"Bathroom": bathroom_result,
"Size": size_result,
"ZonedFor": Zoned_for_result,
"Freehold": Freehold_result,
"Prop_ref": propertyref_result,
"Furnished_status": furnished_result,
"Rent_payment": rent_is_paid_result,
"Building_info": building_result,
"Amenities": Amenities_result,
"Trade_name": tradename_result,
"Licence": licencenum_result,
"RERA_ID": reraid_result,
"Phone_info": phone_result,
"Short_link": link_result,
}
db= MySQLdb.connect("localhost","XXX","XXX","hmm_Raw_Data")
cursor=db.cursor()
#checking phase to stop scrapping
sql = """SELECT Short_link FROM RentalWanted WHERE Short_link=%s"""
rows = cursor.execute(sql,(result["Short_link"],))
if rows>=1:
duplicate_count+=1
print duplicate_count
# if duplicate_count>=15:
# print "The program has started getting duplicates now- The program is terminating"
# sys.exit()
else:
query = """INSERT INTO RentalWanted ({fields}) VALUES ({values})"""
query = query.format(fields=','.join(result), values=','.join(['%s']*len(result)))
cursor.execute(query, result.values())
db.commit()
cursor.close()
db.close()
And better make the column Short_link unique and catch the error, if you try to insert another row with the same link, instead of checking the constraint by hand:
db= MySQLdb.connect("localhost","XXX","XXX","hmm_Raw_Data")
cursor=db.cursor()
try:
query = """INSERT INTO RentalWanted ({fields}) VALUES ({values})"""
query = query.format(fields=','.join(result), values=','.join(['%s']*len(result)))
cursor.execute(query, result.values())
except mysql.connector.IntegrityError:
duplicate_count+=1
print duplicate_count
else:
db.commit()
cursor.close()
db.close()
Apparently there's a backward compatibility issue in MySQL-python version 1.2.5 where it expects a tuple rather than a string when you call execute.
Try this:
rows = cursor.execute(sql,( [link_result] ))

Error when inserting row to table with MySQLdb

What is wrong below?
import MySQLdb as mysql
import datetime
db = mysql.connect("localhost","root","passworld","employees" )
cursor = db.cursor()
sql = "INSERT INTO employee(id, firstname, surname, sex, employmentdate) VALUES (%s, %s, %s, %s, '%s')" %(id, firstname, surname, sex, employmentdate)
dater = datetime.datetime(2005,1,1)
cursor.execute(["012345","Mark", "Rooney", "M", dater])
OperationalError: (1054, "Unknown column 'Mark' in 'field list'")
You should pass your sql statement and params to cursor.execute():
sql = "INSERT INTO employee(id, firstname, surname, sex, employmentdate) VALUES (%s, %s, %s, %s, '%s')"
cursor.execute(sql, ["012345","Mark", "Rooney", "M", dater])
db.commit()

Categories