Python SQLite3不起作用

时间:2015-11-14 06:28:33

标签: python python-2.7 sqlite

我正在Python中使用SQLite3。 Python的版本是2.7我正在使用mac os。

我发现我的代码没有任何问题...... 当我运行它时,我没有得到任何语法错误。 我的编码假设打印出数据库的每个元素。 它根本不打印任何东西。

import sqlite3

createDb = sqlite3.connect('sample.db')

queryCurs = createDb.cursor()

def createTable():
    queryCurs.execute('''CREATE TABLE customers
    (id INTEGER PRIMARY KEY, name TEXT, street TEXT, city TEXT, state TEXT, balance REAL)''')

def addCust(name, street, city, state, balance):
    queryCurs.execute('''INSERT INTO customers (name, street, city, state, balance))
    VALUES (?,?,?,?,?) ''',(name, street, city, state, balance))

def main():
    createTable()

    addCust('test1','123 mel','vancouver','bc', 10000000.00)
    addCust('test2','145 joy','ottawa','on', 10000000.00)
    addCust('test3','521 tick','toronto','on', 10000000.00)
    addCust('test4','5832 tock','burnaby','bc', 10000000.00)

    createDb.commit()

    queryCurs.execute('SELECT * FROM customers')

    for i in queryCurs:
        print "\n"
        for j in i:
            print j

你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

您永远不会致电您的main()功能。 Python不会自动调用函数,main()没有特殊含义。您通常会添加“脚本测试”:

if __name__ == '__main__':
    main()

到模块的末尾,当文件作为脚本运行时调用函数;当您的文件作为模块导入时,__name__包含模块名称而不是'__main__'

当你这样做时,你会发现你有一个SQL语法错误:

Traceback (most recent call last):
  File "test.py", line 33, in <module>
    main()
  File "test.py", line 18, in main
    addCust('test1','123 mel','vancouver','bc', 10000000.00)
  File "test.py", line 13, in addCust
    VALUES (?,?,?,?,?) ''',(name, street, city, state, balance))
sqlite3.OperationalError: near ")": syntax error

在列名列表后面的SQL中有一个)太多,请删除它:

def addCust(name, street, city, state, balance):
    queryCurs.execute('''INSERT INTO customers (name, street, city, state, balance)
    VALUES (?,?,?,?,?) ''',(name, street, city, state, balance))