如何在python中将变量插入sqlite数据库? [英] How to insert variable into sqlite database in python?

查看:91
本文介绍了如何在python中将变量插入sqlite数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码似乎运行良好,没有任何错误,但它只是创建了一个空的数据库文件,其中没有任何内容,无法弄清楚我在这里做错了什么.

My code seems to run fine without any errors but it just creates an empty database file with nothing in it, Cant figure out what i'm doing wrong here.

import sqlite3 as lite
import sys
con = lite.connect('test43.db')

def create_db():
    with con:
        cur = con.cursor()
        cur.execute("DROP TABLE IF EXISTS Contacts")
        cur.execute("CREATE TABLE Contacts (First Name TEXT, Last Name TEXT, Phone TEXT, Email TEXT);")
        cur.execute("INSERT INTO Contacts VALUES (?, ?, ?, ?);", (firstname, lastname, phone, email))
        cur.commit()

#Get user input
print ('Enter a new contact')
print ('')
firstname = input('Enter first name: ')
lastname = input('Enter last name: ')
phone = input('Enter phone number: ')
email = input('Enter Email address: ')

createnewdb = input('Enter 1 to create new db: ')
if createnewdb == 1:
    create_db()
else:
    sys.exit(0)

推荐答案

它没有进入 create_db() 方法,因为 if 子句正在比较 >stringnumber.input() 返回一个字符串,所以你真的应该将它与另一个字符串进行比较..

It's not getting to the create_db() method, as the if clause is comparing a string to a number. input() returns a string, so you really should be comparing it to another string..

尝试以下操作:

if createnewdb == "1":
    create_db()
else:
    sys.exit(0)

然后,您应该在 连接对象,而不是光标..所以也在这里稍微改变一下你的 create_db() 方法:

Then, you should call commit() on the connection object, not the cursor.. so change your create_db() method a little here too:

def create_db():
    with con:
        cur = con.cursor()
        cur.execute("DROP TABLE IF EXISTS Contacts")
        cur.execute("CREATE TABLE Contacts (First Name TEXT, Last Name TEXT, Phone TEXT, Email TEXT);")
        cur.execute("INSERT INTO Contacts VALUES (?, ?, ?, ?);", (firstname, lastname, phone, email))

        ## call commit on the connection...
        con.commit()

那么它应该适合你!

这篇关于如何在python中将变量插入sqlite数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆