(python) Databases, incorrect syntax error - python

I'm completely new to databases, and have put something simple together using the helpful guide that can be located at http://halfcooked.com/presentations/osdc2006/python_databases.html , However it's returning an error that I don't understand
try:
from sqlite3 import dbapi2 as sqlite
except ImportError:
from pysqlite2 import dbapi2 as sqlite
db_connection = sqlite.connect('program.db')
db_curs = db_connection.cursor()
def create_customer(cID, fname, sname, dob):
db_curs.execute("CREATE TABLE " + cID + " ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
db_curs.execute("INSERT INTO " + cID + " (first_name, last_name, date_of_birth) VALUES (fname, sname, dob)")
db_connection.commit()
db_curs.execute("SELECT * FROM " + cID )
create_customer("1", "John", "Farnham", "12/08/95")
create_customer("1", "Indianna", "Jones", "05/05/95")
print db_curs.fetchall()
the error I am receiving is as follows:
Traceback (most recent call last):
File "C:\Users\fin0005\Documents\loyalty.py", line 17, in <module>
create_customer("1", "John", "Farnham", "12/08/95")
File "C:\Users\fin0005\Documents\loyalty.py", line 12, in create_customer
db_curs.execute("CREATE TABLE " + cID + " ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
OperationalError: near "1": syntax error

Add backticks around your table name, so that it doesn't think it's creating an integer as a table name
def create_customer(cID, fname, sname, dob):
db_curs.execute("CREATE TABLE `" + cID + "` ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
db_curs.execute("INSERT INTO `" + cID + "` (first_name, last_name, date_of_birth) VALUES (fname, sname, dob)")
db_connection.commit()
db_curs.execute("SELECT * FROM `" + cID + "`")
# In SQL terms, the following blows up
# create table 2 (id int(10) PRIMARY KEY); Due to the 2 being an integer
# create table `2` (id int(10) PRIMARY KEY); Works, due to the 2 being properly identified with backticks :)
# Here's some code as requested in the comment, everything below this point is a self contained example, please do not copy the function above
def initiate_customer_table(table_name):
db_curs.execute("CREATE TABLE IF NOT EXISTS `" + table_name + "` ( id INTEGER PRIMARY KEY, first_name VARCHAR(20),last_name VARCHAR(30), date_of_birth DATE)")
db_connection.commit()
def create_customer(table_name, fname, sname, dob):
db_curs.execute("INSERT INTO `" + table_name + "` (first_name, last_name, date_of_birth) VALUES (%s, %s, %s)", [fname, sname, dob])
db_connection.commit()
# Fetches the user just created
db_curs.execute("SELECT * FROM `" + table_name + "` WHERE id = %s", [db_curs.insert_id()])
# Returns the user
return db_curs.fetchone()
desired_table_name = 'customers'
initiate_customer_table(desired_table_name)
customer_1 = create_customer(desired_table_name, "Bryan", "Moyles", "1800-01-01")
customer_2 = create_customer(desired_table_name, "Awesome", "Guy", "1800-01-01")
I will also suggest that you go a step further, if you plan on using this code in production, to ensure that all fields are escaped properly for mysql.

Related

How to create table dynamically in python mysql.connector?

I got an error in the 5th line in my code below at '"+uname+"'.
How can I create a table at runtime?
Here is my code :
name = en1.get()
uname = en2.get()
password = en3.get()
sql = "insert into register values ('" + name + "','" + uname + "','" + password + "')"
CreateTable = "CREATE TABLE '"+uname+"'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))"
try:
cur.execute(sql)
cur1.execute(CreateTable)
con.commit()
con1.commit()
messagebox.showinfo("Success", "Your data is registered successfully!")
except:
messagebox.showinfo("Error inserting", "Please change your username and try.")
In the statements with get(), if you get None as a return value then the below statements will fail
name = en1.get() #-- None
sql = "insert into register values ('" + name + "','" + uname + "','" + password + "')"
CreateTable = "CREATE TABLE '"+uname+"'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))"
Try this instead so that if any of the values is None, then below output will be obtained
without causing the error but still the sql query needs to be handled
sql = "insert into register values ('{}','{}','{}')".format(name, uname, password)
CreateTable = "CREATE TABLE '{}'(no INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),amount INT,date DATE,mode VARCHAR(255))".format(name)
print("sql is ", sql)
print("sql is ", CreateTable)
# Output
sql is insert into register values ('None','None','None')
sql is CREATE TABLE 'None'(no INT AUTO_INCREMENT PRIMARY KEY,title VAR
CHAR(255),amount INT,date DATE,mode VARCHAR(255))

Insert datetime.now()

I'm setting up an electronic system that reads electric current and send it into db. The time the system reads the electric current is different from when it's sent into the db.
I'm using Python so I use datetime.datetime.now(). How do I set the INSERT for it to work?
def create_table(self):
create_table_command = "CREATE TABLE sinal(id serial PRIMARY KEY, name varchar(100), medida float, data arr[] )"
self.cursor.execute(create_table_command)
def insert_new_record(self, label, measure, time):
new_record = (label, measure, time)
insert_command = "INSERT INTO sinal(name, medida, data) VALUES('" + new_record[0] + "','" + new_record[1] + "','" + new_record[2] + "')"
pprint(insert_command)
self.cursor.execute(insert_command)
This is the error I get:
psycopg2.errors.UndefinedObject: type "arr[]" does not exist LINE 1:
...l PRIMARY KEY, name varchar(100), medida float, data arr[] )

psycopg2 set PRIMARY KEY from tuple with placeholder

How can I set a primary key in psycopg2 from a tuple of values being looped in from a tuple?
for example i have my tuple
meetattrs = ('id', 'venue', 'date', 'rail', 'weather', 'trackcondition')
and then I want to create the table and extract and insert values. From the meetattrs I wish to set id as the primary key.
conn = psycopg2.connect("")
with conn, conn.cursor() as cur:
# First, create tables.
cur.execute("drop table if exists meetings, races, horses")
cur.execute("create table meetings (id integer PRIMARY KEY, " +
", ".join("%s varchar" % fld for fld in meetattrs)
+ ")")
This however creates this error, unsure how to resolve.
Traceback (most recent call last):
File "racemeeting.py", line 56, in <module>
+ ")")
psycopg2.ProgrammingError: column "id" specified more than once
Your current sql query after the join is performed and the placeholders take their values is:
'create table meetings (id integer PRIMARY KEY, id varchar, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'
id is specified twice.
You can build your query in a much cleaner way:
query_params = " %s integer PRIMARY KEY" + ", %s varchar" * (len(meetattrs) - 1)
And your SQL statement becomes:
"create table meetings (" + query_params % meetattrs + ")"
After the insertion of placeholder values:
'create table meetings (id integer PRIMARY KEY, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'
Be sure your tuple always has its first item as id
In that kind of problem, you should first try to build and control the sql string.
("create table meetings (id integer PRIMARY KEY, " +
", ".join("%s varchar" % fld for fld in meetattrs)
+ ")")
gives:
'create table meetings (id integer PRIMARY KEY, id varchar, venue varchar, date varchar, rail varchar, weather varchar, trackconditionvarchar)'
effectively duplicating id column.
The solution is then trivial: remove first identifier from meetattrs:
cur.execute("create table meetings (id integer PRIMARY KEY, " +
", ".join("%s varchar" % fld for fld in meetattrs[1:])
+ ")")
Alternatively if you cannot be sure that the primary key if the first element:
cur.execute("create table meetings (id integer PRIMARY KEY, " +
", ".join("%s varchar" % fld for fld in meetattrs if fld != 'id')
+ ")")

Python, mysqldb error 1064

So I have the following error:
_mysql_exceptions.ProgrammingError: (1064, "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 'I, Alexander_Bernard16#milton.edu, D0NBT6)' at line 1")
Here's my code:
cnx = MySQLdb.connect(
user=username, passwd=password, host=hostname, db=databaseName)
cursor = cnx.cursor()
cursor.execute("CREATE TABLE if not exists gotchaTable(id int(11) PRIMARY KEY "
"AUTO_INCREMENT, selfFirstName TEXT NOT NULL, selfLastName TEXT NOT NULL, "
"selfGrade TEXT NOT NULL, selfCode TEXT NOT NULL, targetCode TEXT NOT "
"NULL);")
cnx.commit()
add_data = (
"INSERT INTO gotchaTable (selfFirstName, selfLastName, selfGrade, selfCode, targetCode) VALUES ({0}, {1}, {2}, {3}, {4});"
)
studentlist = []
with open('Gotcha.csv', 'rb') as csvfile:
gotchaData = csv.DictReader(csvfile)
for row in gotchaData:
student = Student(
row['First'], row['Last'], row['Class'], row['Email'])
studentlist.append(student)
studentlist = randomList(studentlist)
for x in xrange(1, len(studentlist)):
studentlist[x].target = studentlist[
x + 1] if x < len(studentlist) - 1 else studentlist[0]
cursor.execute(add_data.format(studentlist[x].first, studentlist[x].last,
studentlist[x].grade, studentlist[x].email,
studentlist[x].code, studentlist[x].target.code))
cnx.commit()
print studentlist[x].getData()
And here's my student class:
class Student(object):
"""docstring for Student"""
def __init__(self, f, l, c, e):
self.first = f
self.last = l
self.grade = c
self.email = e
self.code = id_generator()
self.target = None
def getData(self):
return self.first + ' ' + self.last + ' ' + self.grade + ' ' + self.email + ' ' + self.code
Im trying to make a program that gets data from a csv (which already works) and puts it into a SQL table. How do i fix the error 1064, i've tried using "%s" instead of '{0}' but i get the same error. Any suggestions?
the id_generator() method returns a string of random characters.
randomList(a) makes the array random.
Don't use string formatting to parameterize an SQL query - this is dangerous and, as you can see, error-prompt. Instead, let the MySQL driver worry about it:
add_data = """
INSERT INTO
gotchaTable
(selfFirstName, selfLastName, selfGrade, selfCode, targetCode)
VALUES
(%s, %s, %s, %s, %s)
"""
Then, when you call execute() pass parameters in a separate argument:
cursor.execute(add_data, [
studentlist[x].first,
studentlist[x].last,
studentlist[x].grade,
# studentlist[x].email, ALSO WATCH THIS ONE (there are only 5 placeholders in the query)
studentlist[x].code,
studentlist[x].target.code
])

Python MySQLdb: creating database and filling table

I have written a small script to create a MySQL database, create a table (previously erase it if already exists), and insert many entries. When I execute my script, it works creating the database and table, but does not write any entry to the table:
from warnings import filterwarnings
import MySQLdb as db
filterwarnings('ignore', category = db.Warning)
try:
db_name = 'chom'
con = db.connect(user='user', passwd='pass')
cur = con.cursor()
# Create new database
cur.execute('CREATE DATABASE IF NOT EXISTS ' + db_name + ';')
# Create PARAMETERS table
cur.execute('DROP TABLE IF EXISTS ' + db_name + '.PARAMETERS;')
query = ('CREATE TABLE ' + db_name + '.PARAMETERS ('
'idPARAMETERS INT(10) NOT NULL AUTO_INCREMENT, '
'Param_name VARCHAR(30) NULL DEFAULT NULL, '
'Param_value VARCHAR(255) NULL DEFAULT NULL, '
'Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP '
'ON UPDATE CURRENT_TIMESTAMP, '
'User_id VARCHAR(20) NULL DEFAULT NULL, '
'PRIMARY KEY (idPARAMETERS) );'
)
cur.execute(query)
# Insert entries
parameters = ['param1', 'param2', 'param3',
'param4']
for i, param_name in enumerate(parameters, start=1):
cur.execute('INSERT INTO ' + db_name + '.PARAMETERS '
'(idPARAMETERS, Param_name, Param_value, User_id) '
'VALUES (' + str(i) + ', %s, %s, %s);',
(param_name, '', 'user2#localhost'))
cur.close()
con.commit()
except Exception, e:
print 'Error. Last query: ' + str(cur._last_executed)
print e
print 'DB installation script finished'
I can't see where the problem is. Any idea?
The code worked correctly, it was mysql-workbench fault, which was not showing the correct database content (while mysql console client did).

Categories