mysql.connector.ProgrammingError in Python when insert data to table - mysql

I am writing a script to read data from a file by lines and insert each line into MySQL database. I use mysql.connector to do this. Here is a piece of script.
def insert_query(data):
return ("INSERT INTO " + tblname + " (`log`) " + "VALUES " + "(" + "'" + data + "'" + ")")
with open('data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
add_line = insert_query(line)
cursor.execute(add_line)
cursor.commit()
File data.txt has size is 5Mbyte, but it has about 10000 lines.
tblname has 2 field: ID - INT (11) (auto-increment) , log - TEXT
When i run this script, it add to database about 100 lines and crashed. It report a error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for ')'
MySQL version : 5.5.27
How to solve this problem ? Thanks.

Your insert statement is incorrect: 'tblname' is undefined in your function, hence the syntax error. However, there are bigger issues with how you solve it: what if a line in the log has quotes and brackets?
The following code show how to read data from a file and insert it line by line:
stmt = "INSERT INTO {table} (c1) VALUES (%s)".format(table=table_name)
with open('data.txt', 'r') as fp:
for line in fp:
data = (line.strip(),)
cur.execute(stmt, (line.strip(),))
cnx.commit()
Or using executemany(), which would be faster:
with open('data.txt', 'r') as fp:
cur.executemany(stmt, [(line.strip(),) for line in fp])
cnx.commit()

Related

Load data to Salesforce using COPY INTO

I have been trying to load csv data into Snowflake using COPY INTO command
This is the sample data
4513194677~"DELL - ULTRASHARP 32\" MONITOR 4K U3223QE"~""~""
I have tried using below COPY INTO syntax
file_format =
type = 'csv'
field_delimiter = '~'
skip_header = 1
record_delimiter = '\\n'
field_optionally_enclosed_by = '"'
ESCAPE = 'NONE'
ESCAPE_UNENCLOSED_FIELD = 'NONE'
However, getting this error "Found character 'M' instead of field delimiter '~'"
How can I escape the " and load the columns data as DELL - ULTRASHARP 32 " MONITOR 4K U3223QE
If I try to use ESCAPE, I get below error when running the COPY command
[ERROR] ProgrammingError: 001003 (42000): 01a8e01d-3201-36a9-0050-4502537cfc7f: SQL compilation error:
syntax error line 15 at position 43 unexpected '''.
syntax error line 20 at position 20 unexpected ')'.
file_format =
type = 'csv'
field_delimiter = '~'
skip_header = 1
record_delimiter = '\\n'
field_optionally_enclosed_by = '"'
ESCAPE = '\\'
ESCAPE_UNENCLOSED_FIELD = '\\'
Try using two double quotes in the data instead of one without trying to escape the double quote
Data similar to "sample"
You can have your csv formated like below
"Data similar to ""sample"""

Error in MySQL Syntax run on remote server using PyCharm

I am fairly new to programming and I've been trying to implement this code in Python, using PyCharm. I'm running the code via a remote server, using PyCharm on my local computer. It was written by a former colleague, and has been giving a lot of encoding issues since we updated the packages like MySQL and the Python interpreter to 3.8. The MySQL version is 8.0, but this is an update. That was not the version installed originally when the code was written.
This is the full error that I am getting:
findBestMatch
*** WARNING: FoundCity[i] = {'Country': 'Austria', 'Page': 'Contact', 'Confidence': 10, 'Mentions': 1}
WriteToDB
Problem <class 'MySQLdb._exceptions.ProgrammingError'>
Traceback (most recent call last):
File "/remotepath/TextMining/NER/FindLocationStoreSQL.py", line 399, in
WriteToDB(c.title(), cn, idProject, 10, "Contact", "v1", cursor, db, database_country)
File "/remotepath/TextMining/NER/FindLocationStoreSQL.py", line 286, in WriteToDB
cursor.execute(sql,values)
File "/home/localhost/.local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/home/localhost/.local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/home/localhost/.local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
MySQLdb._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 'City text mined, Country from datasource'',Confidence='10',FoundWhere=''Contact'' at line 1")
Process finished with exit code -1
The code sample of the function it is trying to run is below:
def findBestMatch(FoundCity,FoundCountry,database_country):
pair_candidates = []
for i in range(0,5):
for j in range(0,5):
if len(FoundCity)>i and len(FoundCountry)>j:
city_i = FoundCity[i].get('City')
country_j = FoundCountry[j].get('Country')
if city_i != None and country_j != None:
#sql = "SELECT City,Country_CountryName,Longitude,Latitude FROM Semanticon.City where city like '{0}' and Country_CountryName like '{1}' and Population>0 order by Population desc".format(FoundCity[i]['City'].encode('utf-8'),FoundCountry[j]['Country'].encode('utf-8'))
sql = "SELECT City,Country_CountryName,Longitude,Latitude FROM Semanticon.City where city like '{0}' and Country_CountryName like '{1}' and Population>0 order by Population desc".format(
FoundCity[i]['City'], FoundCountry[j]['Country'])
try:
cursor.execute(sql)
except:
db = MySQLdb.connect(host, username, password, database, charset='utf8')
db.set_character_set("utf8")
cursor = db.cursor()
cursor.execute(sql)
resul = cursor.fetchall()
if len(resul)>0:
pair_candidates.append({"City":FoundCity[i]['City'],"Country":FoundCountry[j]['Country'],"Score":(FoundCity[i]["Confidence"]+FoundCountry[j]["Confidence"]+0.5*(FoundCity[i]["Mentions"]+FoundCountry[j]["Mentions"]))})
#return FoundCity[i]['City'],FoundCountry[j]['Country'],FoundCity[i]['Confidence']
else:
if city_i == None:
print("*** WARNING: FoundCity[i] = ", FoundCity[i])
else:
print("*** WARNING: FoundCountry[j] = ", FoundCountry[j])
I had to take the encoding out, hence the commented out 'sql' line. The encoding was causing problems and adding an extra 'b' to the string to be read from the database.
The 'WriteToDB' function that it's complaining about is below:
def WriteToDB(City,Country,ProjectId,Confidence,Location,Version,cursor,db,database_country):
sql = None
if database_country!="":
if database_country == Country:
if City != "":
#sql = "UPDATE ProjectLocation SET City='{0}',DataTrace='{1}',Confidence={2},FoundWhere='{3}' WHERE Projects_idProjects={4} and Country='{5}';".format(City," City text mined, Country from datasource",Confidence,Location,ProjectId,original_database_cntry)
sql = "UPDATE ProjectLocation SET City='%s',DataTrace='%s',Confidence='%s',FoundWhere='%s' WHERE Projects_idProjects='%s' and Country='%s';"
values = (City, " City text mined, Country from datasource", Confidence, Location, ProjectId,
original_database_cntry)
if database_country!=Country:
if Country.encode('utf-8') in database_country:
#sql = "UPDATE ProjectLocation SET City='{0}',DataTrace='{1}',Confidence={2},FoundWhere='{3}' WHERE Projects_idProjects={4} and Country='{5}';".format(
# City, " City text mined, Country from datasource", Confidence, Location, ProjectId,
#original_database_cntry)
sql = "UPDATE ProjectLocation SET City='%s',DataTrace='%s',Confidence='%s',FoundWhere='%s' WHERE Projects_idProjects='%s' and Country='%s';"
values = (City, " City text mined, Country from datasource", Confidence, Location, ProjectId,
original_database_cntry)
else:
print("Country conflict in project:"+str(ProjectId))
else:
#sql = "Insert into ProjectLocation (Type,City,Country,Projects_idProjects,Original_idProjects,IsLocationFromDataset,Confidence,FoundWhere,Version,DataTrace)" \
# "Values ('{0}','{1}','{2}',{3},{4},0,{5},'{6}','{7}','{8}')".format("Main",City,Country,ProjectId,ProjectId,Confidence,Location,Version,"Both minded from text v0.1")
sql = "Insert into ProjectLocation (Type,City,Country,Projects_idProjects,Original_idProjects,IsLocationFromDataset,Confidence,FoundWhere,Version,DataTrace)" \
"Values ('%s','%s','%s','%s',0,'%s','%s','%s','%s','%s')"
values = ("Main", City, Country, ProjectId,ProjectId, Confidence, Location, Version, "Both minded from text v0.1")
if sql!=None:
cursor.execute(sql,values)
db.commit()
I commented out the SQL queries as shown and tried to bind them instead, because it was giving a lot of encoding errors. I'm not sure how to get rid of this error and not end up with the encoding errors yet again.
Can someone help?
UPDATE to the question.
I reverted back all the sql queries, and used the queries with the encoding now (previously commented out) and I am getting 'b's in the output.
Any suggestions on how to properly encode these SQL queries so the binary encoding does not come out as b's in the output?
Here is a sample of the output:
ProjectID,ProjectName,FoundCity,FoundCountry,DatabaseCity,DatabaseCountry,Confidence,FoundWhere,Website
2542, Migrantour Country,,b'',b'',b'',10,Contact,link
3938,GeoSmartCity,,,b'',b'',10,Contact,link

SQL % statement in python returns error

I created 5 tables in mysql workbench 5.7 in which I will pull data from APIgraph queries for a given facebook page.
However, when I run the code, it throws an error:
ProgrammingError: 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, %s)' at line 1
Here is the part of the code which I think contains the error :
#create connection to db
connection = connect_db()
cursor = connection.cursor()
#SQL request for inserting the date of the page into the database
insert_page = ("INSERT INTO page"
"(fb_id, name)"
"VALUES (%s, %s)")
insert_posts = ("INSERT INTO posts "
"(page_id, fb_post_id, message, time_created)"
"VALUES (%s, %s, %s, %s)")
And I finally put the data at the end of the code:
cursor.execute(insert_page, json_pageiddata)
Any ideas? Thanks for helping
EDIT: here is my json_pageiddtata variable, obtained from a URL query with APIgraph:
pageid_url = create_pageid_url(current_page, APP_ID, APP_SECRET)
json_pageiddata = render_to_json(pageid_url)
print json_pageiddata["name"], json_pageiddata["id"]
If you are using data as dictionary u need to specify index name, try to use %(name)s.

Python. I'm creating a phone database and linking it with a python code

I'm trying to make a Python code that searches my sql database. I can make it search the phone model and display the duration of the contract. The problem is that when I try to make it display the price of each tariff, it returns error #1064. I figured out that the column name: "Price/Month" causes error in python so I changed it to PriceperMonth; but this error occurs.
Example of Price per Month:
£ 25.
It has currency symbol. Maybe that is the one that causes the error.
My code:
#!/Python27/python
import mysql.connector
def SearchPhoneByPhone(Model):
conn = mysql.connector.connect(user='root', \
host='127.0.0.1', database ='phone')
cur = conn.cursor()
query = "SELECT phone.Model, tariff.Duration price.PriceperMonth FROM phone, tariff, price \
WHERE phone.Phone_ID = price.Phone_ID AND tariff.Tariff_ID = price.Tariff_ID \
AND phone.Model LIKE '%" + Model + "%'"
cur.execute(query)
print "This model " + Model +" has the following tariffs:"
for (Model, Duration, PriceperMonth) in cur.fetchall():
print Model + " (Duration of the Contract: " + Duration + ")" + " (Price per Month: " + PriceperMonth + ")"
print ""
cur.close()
conn.close()
SearchPhoneByPhone('iPhone 6 Plus')
The error message:
Traceback (most recent call last):
File "C:\Users\Ren25\Dropbox\SAT-0400 Project\Phone Database Connect.py", line 25, in <module>
SearchPhoneByPhone('iPhone 6 Plus')
File "C:\Users\Ren25\Dropbox\SAT-0400 Project\Phone Database Connect.py", line 15, in SearchPhoneByPhone
cur.execute(query)
File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
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 '.PriceperMonth FROM phone, tariff, price WHERE phone.Phone_ID = price.Phone_' at line 1
you forget comma between these 2 columns in select query:
tariff.Duration, price.PriceperMonth
so your query should be:
query = "SELECT phone.Model, tariff.Duration, price.PriceperMonth FROM phone, tariff, price \
WHERE phone.Phone_ID = price.Phone_ID AND tariff.Tariff_ID = price.Tariff_ID \
AND phone.Model LIKE '%" + Model + "%'"

Load Data Infile errors

In the syntax of load infile data i saw that the fields and line clauses are optional. So I used only character set clause for utf8
Here my sql:
cmd = new MySqlCommand("LOAD DATA INFILE " + filename + " INTO TABLE " + tblname + " CHARACTER SET 'UTF8'", conn);
filename is the addresse it's format is: "E:\Macdata\20131228\atelier.sql"
table name is directly taken from database is as : "atelier"
But I get the 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 'E:\Macdata\20131228\atelier.sql INTO TABLE atelier CHARACTER SET 'UTF8'' at line 1
What is the mistake in my query command ?
MYSQLversion is 5.0.10 with XAMPP
After changing the query I begin to receive fatal error number 0 (enclosed filename with ')
cmd = new MySqlCommand("LOAD DATA LOCAL INFILE '" + filename + "' IGNORE INTO TABLE " + tblname + " CHARACTER SET UTF8", conn);
My data file has this form which works on phpmyadmin
INSERT INTO `atelier` VALUES(1, 'Chateau Carbonnieux -1', '2013-12-26', 23, 10, 0, '4 macarons differents', 'mamie', '2013-12-15 11:09:14', 'sabrina', '2013-12-18 05:29:26');
As the error says, your statements is wrong. Quotes are missing in your first statement (see second statement). Check the syntax here:
http://dev.mysql.com/doc/refman/5.6/en/load-data.html
Some sparse notes:
0 is not a fatal error, it's the code for success.
IGNORE handles duplicate rows, not syntax errors.