我对数据库完全陌生,并使用位于http://halfcooked.com/presentations/osdc2006/python_databases.html的有用指南将一些简单的内容放在一起,但是它返回的错误我并非如此理解
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()
我收到的错误如下:
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
答案 0 :(得分:1)
在表名周围添加反引号,以便它不会认为它创建一个整数作为表名
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")
如果您计划在生产中使用此代码,我还建议您更进一步,以确保为mysql正确转义所有字段。