简体   繁体   English

Python SQLite3无法正常工作

[英]Python SQLite3 is not working

I am practing using SQLite3 in Python. 我在Python中练习使用SQLite3。 The version of Python is 2.7 And I am using mac os. Python的版本是2.7,而我使用的是mac os。

I cannot find any problem with my code... When I run it, I do not get any syntax error. 我的代码找不到任何问题...运行它时,没有任何语法错误。 My coding suppose to print out every element of database. 我的编码假设要打印出数据库的每个元素。 It does not print anything at all. 它根本不打印任何内容。

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

Can you tell me what I am doing wrong? 你能告诉我我做错了什么吗?

You never call your main() function. 您永远不会调用 main()函数。 Python doesn't automatically call functions, main() has no special meaning. Python不会自动调用函数, main()没有特殊含义。 You'd normally add a "script test": 您通常会添加“脚本测试”:

if __name__ == '__main__':
    main()

to the end of your module to call a function when the file is run as a script; 当文件作为脚本运行时,在模块末尾调用函数; when your file is imported as a module instead __name__ contains the module name instead of '__main__' . 当您的文件作为模块导入时, __name__包含模块名称而不是'__main__'

When you do, you'll see you have a SQL syntax error: 这样做时,您会看到一个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

You have one too many ) in your SQL following the list of column names, remove it: 在列名列表后的SQL中,您有太多( ) ,请将其删除:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM