我想简单地使用python和sqlite在数据库中创建一个表。但是,我需要用户提供我的数据库名称。我设法做到了:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3 as sqlite
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
def create_table(dbname):
sql = '''\
CREATE TABLE IF NOT EXISTS ''' + dbname + ''' (
ID INTEGER PRIMARY KEY NOT NULL,
FIRSTNAME TEXT,
LASTNAME TEXT,
ACADEMIC_DEGREE TEXT,
DISCIPLINE TEXT
'''
connection = sqlite.connect(dbname, check_same_thread=False)
try:
with connection:
cursor = connection.cursor()
try:
cursor.execute(sql)
except sqlite.DatabaseError, dbe:
print dbe
finally:
connection.close()
tmp = os.path.split(os.path.dirname(os.path.abspath(__file__)))
path = os.path.join(tmp[0], 'researchers.sql')
create_table(path)
但是,我的代码不会创建表,但只会给我一条错误消息:near "/": syntax error
。这段代码出了什么问题? python提到的语法错误在哪里,如何解决这个问题?
此代码有效:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3 as sqlite
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
def create_table(dbname):
sql = '''
CREATE TABLE IF NOT EXISTS ''' + str(dbname.split('.')[0]) + ''' (
ID INTEGER PRIMARY KEY NOT NULL,
FIRSTNAME TEXT,
LASTNAME TEXT,
ACADEMIC_DEGREE TEXT,
DISCIPLINE TEXT
)
'''
connection = sqlite.connect(dbname, check_same_thread=False)
try:
with connection:
cursor = connection.cursor()
try:
cursor.execute(sql)
except sqlite.DatabaseError, dbe:
print dbe
finally:
connection.close()
create_table('researchers.sql')
答案 0 :(得分:1)
表名中不能包含任意字符,当然不是/
,因此您不能create_table(path)
。选择一个简单的表名,例如“研究人员”。
答案 1 :(得分:1)
用这个替换你的sql变量;
sql = '''
CREATE TABLE IF NOT EXISTS ''' + dbname + ''' (
ID INTEGER PRIMARY KEY NOT NULL,
FIRSTNAME TEXT,
LASTNAME TEXT,
ACADEMIC_DEGREE TEXT,
DISCIPLINE TEXT
)
'''