python字典到sqlite插入

时间:2019-03-13 17:51:26

标签: python dictionary sqlite

当我阅读有关SQLLite3和Python的文章时,我尝试了这个简单的字典到数据库方法。我已经尝试了一些stackoverflow论坛,但现在能够弄清楚如何从字典到数据库获取此数据,然后打印出来。下面的代码:

import sqlite3

user_dir={}

#connect a built in function to connect or create db
conn=sqlite3.connect('phonebook.db')

#Create a cursor function which allows us to do sql operations
crsr=conn.cursor()

#Create a Table
#crsr.execute(""" Create Table phonebook(
#            f_name text,
#            phone text)
#            """)

def create_user():
    while True:
        rsp=input('Create new user: Y/N ?')
        if rsp=='y':
                f_name = input('Enter first name: ')
                #First name cannot be empty
                while (len(f_name)==0):
                   print('First name cannot be empty')
                   f_name = input('Enter first name: ')
                phone = input('Enter phone number: ')
                user_dir[f_name]=phone
                #crsr.execute("INSERT INTO phonebook VALUES (?,?)", [user_dir["f_name"], user_dir["phone"]])
                #crsr.executemany("INSERT INTO phonebook VALUES (?,?)", user_dir)
                columns = ', '.join(user_dir.keys())
                sql = "INSERT INTO phonebook VALUES (?,?)" % ('phonebook', columns)
                crsr.execute(sql, user_dir.values())

        if rsp=='n':
            break

    crsr.execute("SELECT * from phonebook")
    print(crsr.fetchall())

每个注释行的错误是不同的。感谢您的时间和帮助。

0 个答案:

没有答案