Python insert data into MySQL - python

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?

Related

How would one return a MySQL query's completion status with mysql.connector?

To start off, here is an example of what I mean by the 'completion status'. This is a query run via MySQL's CLI
mysql> USE DATABASE1;
Database changed
The line,Database Changed is what I am after. The mysql.connector lib for Python only returns the result of queries that return tables of data from what I've seen so far (I will preface this by saying that I am a beginner to SQL in general, so admittedly I have not tried everything out there).
I am trying to create a MySQL gui-based front end as part of a project, so I am trying to replicate the MySQL CLI 'experience',so to speak, to as high a degree as possible. So stuff like getting out such output text is imperative
For instance,
import mysql.connector
mydb = mysql.connector.connect(host = 'localhost', user = 'root', password = key)
mycursor = mydb.cursor()
mycursor.execute('USE DATABASE1')
for i in mycursor:
print(i)
Returns... nothing (Understandable, iterating on the cursor would only provide table data after all). I want to find a way to extract Database Changed through mysql.connector. I've scoured through the docs but can't find any method that would yield me such a thing. Is there a way to eke it out?
You could do (I did after reading this example)
When you only want to print database changes when they happen, you can do something like this:
import mysql.connector
from mysql.connector import errorcode
_current_database = ''
cnx = mysql.connector.connect(host = 'localhost',
user = 'test', password = 'test', auth_plugin='mysql_native_password')
def Execute_MySQL_and_print_result(sqlstatement):
global _current_database
global cnx
try:
mycursor = cnx.cursor(buffered=True)
mycursor.execute(sqlstatement)
if (cnx.database != _current_database):
_current_database = cnx.database
print("Database changed to: ", cnx.database)
j=1
for i in mycursor:
print(j, i)
j=j+1
except mysql.connector.Error as err:
print("OOPS, something went wrong: ", err.errno)
print(err.msg)
Execute_MySQL_and_print_result('USE TEST')
Execute_MySQL_and_print_result('SHOW DATABASES')
Execute_MySQL_and_print_result('USE TEST')
Execute_MySQL_and_print_result('SHOW DATABASES')
Execute_MySQL_and_print_result('SELECT * FROM nonexistingTable')
output:
Database changed to: test
1 ('information_schema',)
2 ('sakila',)
3 ('test',)
4 ('world',)
1 ('information_schema',)
2 ('sakila',)
3 ('test',)
4 ('world',)
OOPS, something went wrong: 1146
Table 'test.nonexistingtable' doesn't exist
I added the numbers before the database names to make it clear when the second SHOW DATABASE is starting output.
Note: The second USE TEST has no output, because active database did not change.

python postgresql select user input

I'm having a problem and I think that I'm missing something very basic. I'm kind of a noob if it comes to programming but I guess I learn quick. I'm trying to make a Python script that asks for user input and then performs Postgresql SELECT. Then, the outcome of SELECT should be put into another script that uses SSH but I can't wrap my head around that SELECT query. There is a basic example of my code, if you have any tips I would appreciate greatly:
print('Diagnostic tool')
print('')
print('Please insert account ID:')
input()
try:
conn = psycopg2.connect("dbname='psql' user='user' host='localhost'
password='pasword'")
cur = conn.cursor()
cur.execute("SELECT * FROM exampletable WHERE acc_id = #userinput ")
cur.fetchall()
except:
print ("Could not establish connection to Database")
As shown above- how do I perform a query that uses SELECT WHERE table name is user input (acc_id)?
you can use format function on a string.
id = input("Please enter your id")
# id should be passed to format.
query = "SELECT * FROM exampletable WHERE acc_id = {} ".format(id)
try:
conn = psycopg2.connect("dbname='psql' user='user' host='localhost'
password='pasword'")
cur = conn.cursor()
cur.execute(query )
cur.fetchall()
except:
print ("Could not establish connection to Database")
You should pass the input as a parameter to the query. If the input string is saved in userInput you can do:
cur.execute("SELECT * FROM exampletable WHERE acc_id = %s", (userInput,))
Note: for input if your purpose is to take just the input without evaluationg as python code you should use the function raw_input().

How to insert variable to database table sqlite3 - Python

Whenever i try to run the following code i get an error saying that theres no such column "title_data", im really confused because "TITLE" is the column not "title_data"
def insertData(self):
title_Data = self.edit_title.text()
year_Data = self.edit_year.text()
rating_Data = self.edit_rating.text()
connection = sqlite3.connect('films.db')
try:
connection.execute("INSERT INTO FILMS (TITLE,YEAR,RATING) VALUES(title_Data,year_Data,rating_Data)")
except sqlite3.IntegrityError:
print("You have already stored this data")
connection.commit()
connection.close()
You're not passing your variables correctly. Instead of
connection.execute("INSERT INTO FILMS (TITLE,YEAR,RATING) VALUES(title_Data,year_Data,rating_Data)")
You should use
connection.execute("INSERT INTO FILMS (TITLE,YEAR,RATING) VALUES(?,?,?)", (title_Data,year_Data,rating_Data))
See the docs for execute() for more information.

Error while testing postgresql database with python

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.

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