I am trying to test the following with python but I get the invalid syntax error:
db = None
try:
db = mdb.connect("localhost","user","pass","dbName")
with db:
cur = db.cursor()
cur.execute("SELECT * from product")
rows = cur.fetchall()
for row in rows:
print row
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
The error is the following:
File "script.py", line 11
with db:
^
SyntaxError: invalid syntax
How do I fix this?
I'd be nice to see all your imports declarations too to see what could be missing from your code. I assume that you at least have the import MySQLdb somewhere. I made a dummy database with a couple of data rows to test this out. Not sure how python let you get away with the indentation blocks being all messed up, but maybe it's just your code indentation posting error on here.
This is the code I tried and seemed to have no issues:
import MySQLdb as mdb
db = None
try:
db = mdb.connect("localhost","user", "password", "test_data")
## with db: ## try taking this out for Python 2.4
cur = db.cursor()
cur.execute("SELECT * FROM PRODUCT")
rows = cur.fetchall()
for row in rows:
print row
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
Related
I often excute sql sentence with mysql.connector
conn = mysql.connector.connect(user='root', password='pass', host='localhost', database='db1')
cur = conn.cursor(buffered=True)
sql = "select * from mysql where symbol = %s and life = %s"
data = (data1,data2)
cur.execute(sql,data)
Normally, this is not problem , but sometimes error happens with some small misstakes.
If I could check sql generated directly, it is the great help for debuging.
select * from mysql where symbol = 'test' and life = 'mylife'
I have tried thanks to #hunzter advice.
try:
cur.execute(sql,data)
except:
pprint(cur._last_executed)
sys.exit()
However it shows
AttributeError: 'MySQLCursorBuffered' object has no attribute '_last_executed'
It is cursor._last_executed. You can print it out, even if exception occurs.
I am having trouble trying to copy a few tables from a mysql server to postgres server. Here is the code that I am currently using to connect, fetch the data and write the data.
my_sqlconnection = MySQLdb.connect(host='a.b.c.d',
user='user',
passwd='admin'
)
try:
pl_sqlconnection = psycopg2.connect("host='x.y.z.c' dbname='user'
user='uadmin' password='uadmin'" )
except psycopg2.Error as e:
print('PSQL: Unable to connect!\n{0}')
print (e)
print (e.pgcode)
print (e.pgerror)
print (traceback.format_exc())
sys.exit(1)
cursor1 = my_sqlconnection.cursor(MySQLdb.cursors.DictCursor)
cursor2 = pl_sqlconnection.cursor()
for db in db_list.db_set:
restaurant_name = db[:-3]
my_sqlconnection.select_db(db)
sql = "SELECT * FROM Orders"
cursor1.execute(sql)
for row in cursor1:
try:
cursor2.execute("INSERT INTO Orders (all the values) Values
(%(all the values)s)", row)
except psycopg2.Error as e:
print ("cannot execute that query!!")
print (e)
print (e.pgcode)
print (e.pgerror)
print (traceback.format_exc())
sys.exit("Some problem occured with that query! leaving early")
sql2 = "SELECT * FROM USERS"
cursor1.execute(sql2)
for row in cursor1:
try:
cursor2.execute("INSERT INTO Users (all the values) Values
(%(all the values)s)", row)
except psycopg2.Error as e:
print ("cannot execute that query!!")
print (e)
print (e.pgcode)
print (e.pgerror)
print (traceback.format_exc())
sys.exit("Some problem occured with that query! leaving early")
cursor1.close()
cursor2.close()
pl_sqlconnection.commit()
my_sqlconnection.close()
pl_sqlconnection.close()
Now the error that I am getting is
python backup.py
cannot execute that query!!
invalid byte sequence for encoding "UTF8": 0xeef1e5
HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".
22021
ERROR: invalid byte sequence for encoding "UTF8": 0xeef1e5
HINT: This error can also happen if the byte sequence does not match
the encoding expected by the server, which is controlled by "client_encoding".
This error is shown specifically when I am trying to execute the 2nd query. When I run only the 1st query, everything runs as it is supposed to. Both the tables are present in the same database. Why is it that the encoding error is shown while executing the 2nd query.
I've encounter a problem when i try to insert values into mysql using python connector.
The problem is that i'm trying to pass an input as a value in mysql, but the input is added as name of the table instead of value of field. Can anyone let me now what am i doing wrong?
My code is:
import mysql.connector
from mysql.connector import errorcode
def main():
try:
connection= mysql.connector.connect(user='root',passwd='',host='localhost',port='3306', database='game_01')
print("Welcome")
name_of_char = input("Your name?: ")
con = connection.cursor()
con.execute("INSERT into charachter (name,intel,strenght,agil) values(%s,0,0,0)" % str(name_of_char))
con.execute("SELECT * FROM charachter")
for items in con:
print(items[1])
except mysql.connector.Error as err:
print(err)
else:
connection.close()
main()
Thanks.
P.S
The error is : 1054: Unknown column in 'field list'. I forgot to mention that in the post. It seems if i enter the tables attribute,it will work but won't add any value.
if you using MySQLdb driver , after execute the query that insert into database or update , you should use connection.commit() to complete saving operation.
try this:
con = connection.cursor()
con.execute("INSERT into `charachter` (`name`,`intel,`strenght`,`agil`) values('%s',0,0,0)" % str(name_of_char))
connection.commit()
if you use any other driver , you should set the auto_commit option true.
see this:
How can I insert data into a MySQL database?
I wanted to start into using databases in python. I chose postgresql for the database "language". I already created several databases, but now I want simply to check if the database exists with python. For this I already read this answer: Checking if a postgresql table exists under python (and probably Psycopg2) and tried to use their solution:
import sys
import psycopg2
con = None
try:
con = psycopg2.connect(database="testdb", user="test", password="abcd")
cur = con.cursor()
cur.execute("SELECT exists(SELECT * from information_schema.testdb)")
ver = cur.fetchone()[0]
print ver
except psycopg2.DatabaseError, e:
print "Error %s" %e
sys.exit(1)
finally:
if con:
con.close()
But unfortunately, I only get the output
Error relation "information_schema.testdb" does not exist
LINE 1: SELECT exists(SELECT * from information_schema.testdb)
Am I doing something wrong, or did I miss something?
Your question confuses me a little, because you say you want to look to see if a database exists, but you look in the information_schema.tables view. That view would tell you if a table existed in the currently open database. If you want to check if a database exists, assuming you have access to the 'postgres' database, you could:
import sys
import psycopg2, psycopg2.extras
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
dbname = 'db_to_check_for_existance'
con = None
try:
con = psycopg2.connect(database="postgres", user="postgres")
cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("select * from pg_database where datname = %(dname)s", {'dname': dbname })
answer = cur.fetchall()
if len(answer) > 0:
print "Database {} exists".format(dbname)
else:
print "Database {} does NOT exist".format(dbname)
except Exception, e:
print "Error %s" %e
sys.exit(1)
finally:
if con:
con.close()
What is happening here is you are looking in the database tables called pg_database. The column 'datname' contains each of the database names. Your code would supply db_to_check_for_existance as the name of the database you want to check for existence. For example, you could replace that value with 'postgres' and you would get the 'exists' answer. If you replace the value with aardvark you would probably get the does NOT exist report.
If you're trying to see if a database exists:
curs.execute("SELECT exists(SELECT 1 from pg_catalog.pg_database where datname = %s)", ('mydb',))
It sounds like you may be confused by the difference between a database and a table.
I am trying to import a large text file into a MySQL database. The SQL statement is as follows:
LOAD DATA INFILE '/tmp/epf/full/album_popularity_per_genre'
INTO TABLE album_popularity_per_genre
CHARACTER SET UTF8 FIELDS TERMINATED BY X'01' LINES TERMINATED BY '\n'
IGNORE 45 LINES (export_date, storefront_id, genre_id, album_id, album_rank)
The above works when I run it in phpMyAdmin, however when I write a simple function in Python that uses the above SQL statement I get an error.
Here is the Python code,
def test():
dbConnection = MySQLdb.connect(
charset='utf8',
host='localhost',
user='root',
passwd='root',
db='epf')
cursor = dbConnection.cursor()
exStr = """LOAD DATA INFILE '/tmp/epf/full/album_popularity_per_genre'
INTO TABLE album_popularity_per_genre CHARACTER SET UTF8
FIELDS TERMINATED BY X'01' LINES TERMINATED BY '\n'
IGNORE 45 LINES
(export_date, storefront_id, genre_id, album_id, album_rank)"""
try:
cursor.execute(exStr)
except MySQLdb.Warning, e:
print "Warning %s" % (str(e))
except MySQLdb.IntegrityError, e:
print "Error %d: %s" % (e.args[0], e.args[1])
#Clean up
cursor.close()
dbConnection.close()
The error I get is as follows,
Warning Data truncated for column 'album_rank' at row 1
My question now is, why does the raw SQL statement work but when I try to run the Python code, no data is imported into the database?
The Python DBAPI is implicitly transactional. Try adding dbConnection.commit() after the execute.