Blender database using Python (errors) - python

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.

Related

QODBC connecting to Python

I am using QODBC Driver to connect to my Quickbooks Data. Until now, I was the QODBC directly in Power BI/Excel and QODBC works perfectly fine there. But today, I tried to connect to QODBC using python and it is giving me the following error
The python code I am using is this
import pyodbc
cn = pyodbc.connect('DSN=QuickBooks Data 64-Bit QRemote;')
cursor = cn.cursor()
cursor.execute("SELECT Top 10 Name FROM Customer")
for row in cursor.fetchall():
print (row)
cursor.close()
cn.close()
Can anyone see what's the reason for this error?
After a lot of googling, I found the answer. I don't know why but the pyodbc.connect statement requires one more parameter i.e. "autocommit=True". So, the updated code now looks like this and it is working perfectly fine.
import pyodbc
# pyodbc.pooling = False
cn = pyodbc.connect('DSN=QuickBooks Data 64-Bit QRemote',autocommit=True)
cursor = cn.cursor()
cursor.execute("SELECT Top 10 Name FROM Customer")
for row in cursor.fetchall():
print (row)
cursor.close()
cn.close()

Check the SQL sentence generated by excute python 3.5 mysql.connecter

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.

Python insert data into MySQL

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?

Fast MySQL Import

Writing a script to convert raw data for MySQL import I worked with a temporary textfile so far which I later imported manually using the LOAD DATA INFILE... command.
Now I included the import command into the python script:
db = mysql.connector.connect(user='root', password='root',
host='localhost',
database='myDB')
cursor = db.cursor()
query = """
LOAD DATA INFILE 'temp.txt' INTO TABLE myDB.values
FIELDS TERMINATED BY ',' LINES TERMINATED BY ';';
"""
cursor.execute(query)
cursor.close()
db.commit()
db.close()
This works but temp.txt has to be in the database directory which isn't suitable for my needs.
Next approch is dumping the file and commiting directly:
db = mysql.connector.connect(user='root', password='root',
host='localhost',
database='myDB')
sql = "INSERT INTO values(`timestamp`,`id`,`value`,`status`) VALUES(%s,%s,%s,%s)"
cursor=db.cursor()
for line in lines:
mode, year, julian, time, *values = line.split(",")
del values[5]
date = datetime.strptime(year+julian, "%Y%j").strftime("%Y-%m-%d")
time = datetime.strptime(time.rjust(4, "0"), "%H%M" ).strftime("%H:%M:%S")
timestamp = "%s %s" % (date, time)
for i, value in enumerate(values[:20], 1):
args = (timestamp,str(i+28),value, mode)
cursor.execute(sql,args)
db.commit()
Works as well but takes around four times as long which is too much. (The same for construct was used in the first version to generate temp.txt)
My conclusion is that I need a file and the LOAD DATA INFILE command to be faster. To be free where the textfile is placed the LOCAL option seems useful. But with MySQL Connector (1.1.7) there is the known error:
mysql.connector.errors.ProgrammingError: 1148 (42000): The used command is not allowed with this MySQL version
So far I've seen that using MySQLdb instead of MySQL Connector can be a workaround. Activity on MySQLdb however seems low and Python 3.3 support will probably never come.
Is LOAD DATA LOCAL INFILE the way to go and if so is there a working connector for python 3.3 available?
EDIT: After development the database will run on a server, script on a client.
I may have missed something important, but can't you just specify the full filename in the first chunk of code?
LOAD DATA INFILE '/full/path/to/temp.txt'
Note the path must be a path on the server.
To use LOAD DATA INFILE with every accessible file you have to set the
LOCAL_FILES client flag while creating the connection
import mysql.connector
from mysql.connector.constants import ClientFlag
db = mysql.connector.connect(client_flags=[ClientFlag.LOCAL_FILES], <other arguments>)

Python, Sqlite not saving results on the file

I have this code in Python:
conn = sqlite3.connect("people.db")
cursor = conn.cursor()
sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
conn.commit()
sql = 'insert into people VALUES (3, "test")'
cursor.execute(sql)
conn.commit()
sql = 'insert into people VALUES (5, "test")'
cursor.execute(sql)
conn.commit()
print 'Printing all inserted'
cursor.execute("select * from people")
for row in cursor.fetchall():
print row
cursor.close()
conn.close()
But seems is never saving to the database, there is always the same elements on the db as if it was not saving anything.
On the other side If I try to access the db file via sqlite it I got this error:
Unable to open database "people.db": file is encrypted or is not a database
I found on some other answers to use conn.commit instead of conn.commit() but is not changing the results.
Any idea?
BINGO ! people! I Had the same problem. One of thr reasons where very simple. I`am using debian linux, error was
Unable to open database "people.db": file is encrypted or is not a database
database file was in the same dir than my python script
connect line was
conn = sqlite3.connect('./testcases.db')
I changed this
conn = sqlite3.connect('testcases.db')
! No dot and slash.
Error Fixed. All works
If someone think it is usefull, you`re welcome
This seems to work alright for me ("In database" increases on each run):
import random, sqlite3
conn = sqlite3.connect("people.db")
cursor = conn.cursor()
sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
for x in xrange(5):
cursor.execute('insert into people VALUES (?, "test")', (random.randint(1, 10000),))
conn.commit()
cursor.execute("select count(*) from people")
print "In database:", cursor.fetchone()[0]
You should commit after making changes i.e:
myDatabase.commit()
can you open the db with a tool like sqlite administrator ? this would proove thedb-format is ok.
if i search for that error the solutions point to version issues between sqlite and the db-driver used. maybe you can chrck your versions or AKX could post the working combination.
regards,khz

Categories

Resources