I have the following error :
db = MySQLdb.connect(host="localhost", # host
user="root", # username
passwd="", # password
db="test",charset='utf8') #
cur = db.cursor()
x = "испытание" # random unicode characters
sql = "INSERT INTO links(test) VALUES(N'%s');"
lst = ( x ) #x is unicode data
cur.execute(sql,lst)
The error I get is : MySQL Error [1064]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax ...
x = "испытание" # random unicode characters
(What Python version are you using? If 2.x, those are not Unicode characters, they're bytes.)
sql = "INSERT INTO links(test) VALUES(N'%s');"
When you use parameterised queries, you don't include the string literal delimiters ''. For MySQLdb where the parameter marker is %s, it should just be:
sql = "INSERT INTO links(test) VALUES(%s);"
(Note also NVARCHAR is unnecessary in MySQL.)
lst = ( x ) #x is unicode data
Here lst is the same value as x, you haven't got a tuple. If you really want a tuple-of-one then say (x,), but probably using an actual list [x] is clearer.
what value are you trying to insert? nothing. what does N'%s' represents. I guess you are trying to insert from a form so I have work on this code, tested it and is running.
First create database with 2 column employee_id and lastname. Then test this code. it will work for you. If you get it right please tick this as answer. Sectona...
#!c:/python25/python
import MySQLdb
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# get form data from form field
employee_id = form.getvalue('employee_id')
lastname = form.getvalue('lastname')
# Open database connection
db = MySQLdb.connect("localhost","sectona","sectona90","sectona_db" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "INSERT INTO EMPLOYEE(employee_id, \
lastname) \
VALUES ('%s', '%s')" % \
(employee_id, lastname)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<body>'
print '<h2>Data Submitted Successfully</h2>'
print "<b>Employee Identity:</b> %s<br>" % (employee_id)
print "<b>Last Name:</b> %s<br>" % (lastname)
print '</body>'
print '</html>'
Related
I'm having a problem with a Python script, the if branch it's not executed, no matter what parameters I give to the script. Is it something wrong with my code? I'm executing an HTML form and the result was OK until I've added some content to the else statement..I've tried everything but it still doesn't want to work...
#!/usr/bin/python3
import pymysql
import cgi
from http import cookies
# Open database connection
db = pymysql.connect("localhost","superadmin","123","dinamic" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
data=cgi.FieldStorage()
a=data.getvalue('e1')
b=data.getvalue('p1')
# Prepare SQL query to fetch a record into the database.
sql = "SELECT id, email, password FROM register WHERE email = %s AND password = %s"
try:
# Execute the SQL command
cursor.execute(sql, (a, b))
# Commit your changes in the database
db.commit()
c=cookies.SimpleCookie()
# assign a value
c['mou']=a
# set the xpires time
c['mou']['expires']=24*60*60
# print the header, starting with the cookie
print (c)
print("Content-type: text/html", end="\r\n\r\n", flush=True);
print('''<html><head><title>First python script for Security and Encrpytion class</title></head><body><center><h2>Successfully login!</h2><br><img src='image/2.gif'></body></html>''');
except:
db.commit()
print("Content-type: text/html", end="\r\n\r\n", flush=True);
print("<html>");
print("<body>");
print("<center>")
print("<h2>Fail to login!</h2>");
print("<img src='image/dinamic.gif'>");
print("</body>");
print("</html>");
# Rollback in case there is any error
db.rollback()
cursor.execute() doesn't return the number of rows that were selected. You can call cursor.fetchone() to see if it returns a row.
There's also no need to call db.commit() since you haven't made any changes.
try:
# Execute the SQL command
cursor.execute(sql, (a, b)))
row = cursor.fetchone()
if row:
c=cookies.SimpleCookie()
# assign a value
c['mou']=a
# set the xpires time
c['mou']['expires']=24*60*60
# print the header, starting with the cookie
print (c);
print ("Content-type: text/html", end="\r\n\r\n", flush=True);
print("");
print('''<html><head><title>Security & Encryption class - First script</title></head><body><h2>successfully login!</h2>''');
print("<center>");
print("<img src='image/successfully.gif'>");
print("</center>");
print("</body></html>");
else:
print ("Content-type: text/html", end="\r\n\r\n", flush=True)
print("<html>")
print("<body>")
print("<center>")
print("<h2>Login fail!</h2>")
print("<img src='image/dinamic.gif'>")
print("<br><br>")
print('<button id="myButton" class="float-left submit-button" >Home</button>')
print('''<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "index.html";
};
</script>''');
print("</center>");
print("</body>");
print("</html>");
except:
# Rollback in case there is any error
db.rollback()
My code executes a query and then for each row in the result set tries to execute another query using values from that row.
import MySQLdb as mdb
try:
con = mdb.connect('localhost', 'root', '', 'cccorder_uk');
with con:
cur = con.cursor()
cur.execute("SELECT code, name, box_size, commodity_code, country_of_origin FROM cccorder_uk.stocks")
rows = cur.fetchall()
for row in rows:
# split the code and take colour and size
code = row[0].split('-')
product_code = code[0]
sql = """SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style='%s'""" % (product_code,)
cur.execute(sql)
results = cur.fetchall()
print results
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
When I print results I get an empty tuple, but if I hard code the product_code, for example sql = """SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style='EP22'""", this returns the results I expect.
Why is my code printing an empty tuple?
Python's string-format operator % isn't smart enough to quote args for MySQL -- pass args to the database execute function, which will pass the args to MySQL correctly.
Example:
cur.execute("SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style=%s", product_code)
See: How can I format strings to query with mysqldb in Python?
I am writing a script that reads data from one table, translates text in one of the columns into German using Google Translate API and load the data back into another table. Everything works except the last step which is the insert into the second table. I printed out the sql statement that is constructed in the script. If i hard code that output and execute the SQL it works just fine. But if i pass it as an argument it fails with the following error:
pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.2(w) Driver][mysqld-5.6.12-log]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 'Pipedly' at line 1 (1064) (SQLExecDirectW)")
The script is as follows (masked db credentials & API key). Please read the comments in the script to follow my description above. Thanks to everyone for the help
import pyodbc
import json
import collections
import urllib
import urlparse
import os
import time
import string
def insertData(databaseName, tableName, insertList):
insertStatement = "INSERT INTO " + databaseName + "." + tableName
for setLine in insertList:
insertStatement = insertStatement + setLine
return insertStatement
def createInsertFtpStatusList(customer, text, location, channel):
insertList = []
insertList.append("(`customer`, ")
insertList.append("`text`, ")
insertList.append("`location`, ")
insertList.append("`channel`) ")
insertList.append(" VALUES ('%s', '%s', '%s', '%s');" % (customer, text, location, channel))
return insertList
def url_fix(s, charset='utf-8'):
if isinstance(s, unicode):
s = s.encode(charset, 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
cnxn = pyodbc.connect("DSN=*mydsn*;UID=*username*; PWD=*password*")
cursor = cnxn.cursor()
cursor.execute("""
SELECT customer, replace(text,'#','') as text, location, channel FROM feeds.vw_pp;
""")
url1="https://www.googleapis.com/language/translate/v2?key=*myAPIkey*&q="
url2="&source=en&target=de"
rows = cursor.fetchall()
for field in rows:
text= field.text
text= text.replace(" ", "%20")
url=url1 + text + url2
url = url_fix(url)
result = urllib.urlopen(url)
data = json.load(result)
ts_text= data["data"]["translations"][0]["translatedText"]
ts_text= ts_text.replace("% 20% 20","")
ts_text= ts_text.replace(" 20%","")
ts_text= ts_text.replace("%","")
ts_text= ts_text.replace("20","")
ts_text= ts_text.replace(" "," ")
insertList= createInsertFtpStatusList(field.customer, ts_text, field.location, field.channel)
sqlStatement= '"' + insertData("feeds", "translated_pp", insertList) + '"'
print sqlStatement
# The sql statement that prints above:
# "INSERT INTO feeds.translated_pp(`customer`, `text`, `location`, `channel`) VALUES ('Pipedly', 'pipedly kommen und seine gehen bis fantastisch sein!', '', 'Facebook');"
# Success - If i copy paste the statement above and execute hardcoded as below, it works just fine.
cnxn.execute("INSERT INTO feeds.translated_pp(`customer`, `text`, `location`, `channel`) VALUES ('Pipedly', 'pipedly kommen und seine gehen bis fantastisch sein!', '', 'Facebook');"
)
# Fail - But if i pass the string as an argument it fails :(
cnxn.execute(sqlStatement)
Don't interpolate data into SQL statements yourself; leave proper escaping to the database adapter by using SQL parameters:
sqlStatement = "INSERT INTO feeds.translated_pp(`customer`, `text`, `location`, `channel`) VALUES (%s, %s, %s, %s)"
cnxn.execute(sqlStatement, (field.customer, ts_text, field.location, field.channel))
The database adapter then ensures that each value is properly escaped, including handling of embedded quotes in the value.
I get the error when running this code:
import sqlite3
user_name = raw_input("Please enter the name: ")
user_email = raw_input("Please enter the email: ")
db = sqlite3.connect("customer")
cursor=db.cursor()
sql = """INSERT INTO customer
(name, email) VALUES (?,?);,
(user_name, user_email)"""
cursor.execute(sql)
Why is this happening?
While the other posters are correct about your statement formatting you are receiving this particular error because you are attempting to perform multiple statements in one query (notice the ; in your query which separates statements).
From Python sqlite3 docs:
"execute() will only execute a single SQL statement. If you try to execute more than one
statement with it, it will raise a Warning. Use executescript() if you want to execute
multiple SQL statements with one call."
https://docs.python.org/2/library/sqlite3.html
Now your statement will not execute properly even if you use executescript() because there are other issues with the way it is formatted (see other posted answers). But the error you are receiving is specifically because of your multiple statements. I am posting this answer for others that may have wandered here after searching for that error.
Use executescript instead of execute
execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.
https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute
You have a ;, in the middle of the query string - that is an invalid syntax. Pass a dictionary as a second argument to execute if you want to use a named parameter binding.
sql = "INSERT INTO customer (name, email) VALUES (:name, :email)"
cursor.execute(sql, {'name':user_name, 'email':user_email})
Try this:
sql = """INSERT INTO customer
(name, email) VALUES (?,?)"""
cursor.execute(sql, (user_name, user_email))
import sqlite3
def DB():
List = {"Name":"Omar", "Age":"33"}
columns = ', '.join("" + str(x).replace('/', '_') + "" for x in List.keys())
values = ', '.join("'" + str(x).replace('/', '_') + "'" for x in List.values())
sql_qry = "INSERT INTO %s ( %s ) values (?,?) ; ( %s )" % ('Table Name', columns, values)
conn = sqlite3.connect("DBname.db")
curr = conn.cursor()
# curr.execute("""create table if not exists TestTable(
# Name text,
# Age text
# )""")
# print columns
# print values
# print sql
# sql = 'INSERT INTO yell (Name , Age) values (%s, %s)'
curr.execute(sql_qry)
DB()
I have following method that I select all the ids from table and append them to a list and return that list. But when execute this code I end up getting tuple indicies must be integers... error. I have attached the error and the print out along with my method:
def questionIds(con):
print 'getting all the question ids'
cur = con.cursor()
qIds = []
getQuestionId = "SELECT question_id from questions_new"
try:
cur.execute(getQuestionId)
for row in cur.fetchall():
print 'printing row'
print row
qIds.append(str(row['question_id']))
except Exception, e:
traceback.print_exc()
return qIds
Printing what my method does:
Database version : 5.5.10
getting all the question ids
printing row
(u'20090225230048AAnhStI',)
Traceback (most recent call last):
File "YahooAnswerScraper.py", line 76, in questionIds
qIds.append(str(row['question_id'][0]))
TypeError: tuple indices must be integers, not str
The python standard mysql library returns tuples from cursor.execute. To get at the question_id field you'd use row[0], not row['question_id']. The fields come out in the same order that they appear in the select statement.
A decent way to extract multiple fields is something like
for row in cursor.execute("select question_id, foo, bar from questions"):
question_id, foo, bar = row
There are multiple cursor types in the MySQLdb module. The default cursor returns the data in a tuple of tuples. When we use a dictionary cursor, the data is sent in a form of Python dictionaries. This way we can refer to the data by their column names. Source
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FROM Writers LIMIT 4")
rows = cur.fetchall()
for row in rows:
print row["Id"], row["Name"]
I know the question is old, but I found another way to do it that I think it is better than the accepted solution. So I'll just leave it here in case anyone needs it.
When creating the cursor you can use
cur = connection.cursor(dictionary=True);
which will allow you to do exactly what you want without any additional modifications.
rows = cur.fetchall()
for row in rows:
print "%s %s %s" % (row["Id"], row["Name"], row["Price"])
you can see here: enter link description here ,I think its your want
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
con = lite.connect('test.db')
with con:
con.row_factory = lite.Row # its key
cur = con.cursor()
cur.execute("SELECT * FROM Cars")
rows = cur.fetchall()
for row in rows:
print "%s %s %s" % (row["Id"], row["Name"], row["Price"])
To retrieve data from database use dictionary cursor
import psycopg2
import psycopg2.extras
con = psycopg2.connect(database="test", user="test", password="test", host="localhost", port="5432")
if con != None:
print "Connection Established..!\n"
else:
print "Database Connection Failed..!\n"
cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("SELECT * FROM emp")
rows = cur.fetchall()
for row in rows:
print "%s %s %s" % (row["id"],row["name"],row["address"])
print "\nRecords Display Successfully"
con.commit()
con.close()
Integer indices are not allowed. To get it working you can declare the DICT as specified below:
VarName = {}
Hope this works for you.
row is a tuple. When you do row['question_id'], you are trying to access a tuple using a string index which gives you an error.