您的位置:首页 > 编程语言 > Python开发

python使用sqlite的tips和bugs

2017-09-18 15:09 246 查看
教程参考SQLite - Python

1、insert变量

conn = sqlite3.connect('tieba.db')
c = conn.cursor()
c.execute("INSERT INTO TIEBA (CONTENT,DATE) VALUES ('%s','%s')" % (reply,date));
conn.commit()
conn.close()


replay和date是变量。

2、查询内容是否存在

conn = sqlite3.connect('tieba.db')
c = conn.cursor()
c.execute("SELECT * from TIEBA where CONTENT = '%s'" % reply)
if(len(c.fetchall())>0):
print("存在")
else:
print("不存在")


replay是变量。

c.fetchall()得到上句指令select到的内容个数,c.fetchall()只有第一次调用时返回正确的内容个数,一个错误的示例如下:

conn = sqlite3.connect('tieba.db')
c = conn.cursor()
c.execute("SELECT * from TIEBA where CONTENT = '%s'" % reply) #假设replay的内容在数据库中已存在,则查到的内容长度应为1
print(len(c.fetchall())) #在这里打印得到1
if(len(c.fetchall())>0): #再调用c.fetchall()就会得到0
print("存在")
else:
print(len(c.fetchall())) #跳到else,打印0
print("不存在")


3、sqlite3.OperationalError: near “hhhhhhhh”: syntax error

查询的时候报了这么个错。查询代码和上面一下,还是这个

conn = sqlite3.connect('tieba.db')
c = conn.cursor()
c.execute("SELECT * from TIEBA where CONTENT = '%s'" % reply)
if(len(c.fetchall())>0):
print("存在")
else:
print("不存在")


查看了一下出这个错时的replay的内容,发现是h’hhhhhhhhh

于是把’给删掉,就没错了。所以代码改成

conn = sqlite3.connect('tieba.db')
c = conn.cursor()
reply = reply.replace("'","")
c.execute("SELECT * from TIEBA where CONTENT = '%s'" % reply)
if(len(c.fetchall())>0):
print("存在")
else:
print("不存在")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: