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.
Related
I'm using Blender 2.74 and Python 3.4 with the correct connector for MySQL. (By the way, I'm just a beginner in using Blender and Python.)
What I want is to make a login UI and save the inputted name into the database, but my code seems a bit off or wrong. When I try to run the code, it didn't save the value in the variable, but when i try to run it in python IDE (PyCharm) it worked.
Here's the code:
import sys
sys.path.append('C:\Python34\Lib\site-packages')
sys.path.append('C:\Python34\DLLs')
import mysql.connector
import bge
bge.render.showMouse(1)
cont = bge.logic.getCurrentController()
own = cont.owner
sensor = cont.sensors ["enter"]
pname = own.get("prpText")
enter = cont.sensors ["enter"]
numpadenter = cont.sensors ["numpadenter"]
if enter.positive or numpadenter.positive:
db = mysql.connector.connect(user='root', password='', host='localhost', database='dbname')
cursor = db.cursor()
#1st:
cursor.execute("INSERT INTO tblname VALUE(%s", (var))
#2nd:
#cursor.execute("INSERT INTO storymode VALUES({})" .format(pname))
#this are the other codes that i have tried so far:
#add_player = ("INSERT INTO tblname " "(TblColumnName) " "VALUES (%s)")
#data_player = (var)
#cursor.execute(add_player, data_player)
#cursor.execute("INSERT INTO tblname" "(TblColumnName)" "VALUES (%(var)s)")
db.commit()
db.close()
When I run the 1st code the error is:
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 the right syntax to use near '%s' at line 1.
When I run the second code:
Unknown column 'data' in 'field list'
Can someone help me to fix this? or Do I need some add-ons in blender for it to work?
Thank you very much for reading my post and for the people who will give their opinions.
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 currently connecting to a Sybase 15.7 server using sybpydb. It seems to connect fine:
import sys
sys.path.append('/dba/sybase/ase/15.7/OCS-15_0/python/python26_64r/lib')
sys.path.append('/dba/sybase/ase/15.7/OCS-15_0/lib')
import sybpydb
conn = sybpydb.connect(user='usr', password='pass', servername='serv')
is working fine. Changing any of my connection details results in a connection error.
I then select a database:
curr = conn.cursor()
curr.execute('use db_1')
however, now when I try to run queries, it always returns None
print curr.execute('select * from table_1')
I have tried running the use and select queries in the same execute, I have tried including go commands after each, I have tried using curr.connection.commit() after each, all with no success. I have confirmed, using dbartisan and isql, that the same queries I am using return entries.
Why am I not getting results from my queries in python?
EDIT:
Just some additional info. In order to get the sybpydb import to work, I had to change two environment variables. I added the lib paths (the same ones that I added to sys.path) to $LD_LIBRARY_PATH, i.e.:
setenv LD_LIBRARY_PATH "$LD_LIBRARY_PATH":dba/sybase/ase/15.7/OCS-15_0/python/python26_64r/lib:/dba/sybase/ase/15.7/OCS-15_0/lib
and I had to change the SYBASE path from 12.5 to 15.7. All this was done in csh.
If I print conn.error(), after every curr.execute(), I get:
("Server message: number(5701) severity(10) state(2) line(0)\n\tChanged database context to 'master'.\n\n", 5701)
I completely understand where you might be confused by the documentation. Its doesn't seem to be on par with other db extensions (e.g. psycopg2).
When connecting with most standard db extensions you can specify a database. Then, when you want to get the data back from a SELECT query, you either use fetch (an ok way to do it) or the iterator (the more pythonic way to do it).
import sybpydb as sybase
conn = sybase.connect(user='usr', password='pass', servername='serv')
cur = conn.cursor()
cur.execute("use db_1")
cur.execute("SELECT * FROM table_1")
print "Query Returned %d row(s)" % cur.rowcount
for row in cur:
print row
# Alternate less-pythonic way to read query results
# for row in cur.fetchall():
# print row
Give that a try and let us know if it works.
Python 3.x working solution:
import sybpydb
try:
conn = sybpydb.connect(dsn="Servername=serv;Username=usr;Password=pass")
cur = conn.cursor()
cur.execute('select * from db_1..table_1')
# table header
header = tuple(col[0] for col in cur.description)
print('\t'.join(header))
print('-' * 60)
res = cur.fetchall()
for row in res:
line = '\t'.join(str(col) for col in row)
print(line)
cur.close()
conn.close()
except sybpydb.Error:
for err in cur.connection.messages:
print(f'Error {err[0]}, Value {err[1]}')
Hi im having issues with a sql query it works perfect in console, but when i implement into python it seems to work perfect no errors but when i check the database it hasnt worked, yet with the console it does work the same no errors yet when i check db the data is there... exact same query i use.
Any ideas?
UPDATE ex SET fbsiteurl = stringvarible, fbsitesource = '' WHERE id = 23123;
in python:
cur = con.cursor()
sqlquery = "UPDATE ex SET fbsiteurl = '"+somevarible+"', fbsitesource = '"+somevarible+"' WHERE id = %d;" % recordid
print sqlquery
cur.execute(sqlquery)
query shows up fine in print no issues, if i copy the print out and paste it into a mysql console it works perfect everytime, just come python it acts like it works but dosnt really 0_o
connection.autocommit(), or you need to do connection.commit()
Been there :) you need to close the cursor
This little gotcha continues to this day. Just to clarify, I had to use both of the above answers, as in:
cur = self.db.cursor()
try:
cur.execute(sqlcommand)
self.db.commit()
res = cur.fetchall()
except res is not None:
print(res)
finally:
cur.close()