Python3和Sqlite3无法插入

时间:2015-04-26 21:52:22

标签: python-3.x sqlite

我正在尝试编写一个函数来进行简单的插入。 这是我到目前为止所尝试的内容

#! /usr/bin/env python3
#import
import sqlite3 as lite

#trying an insert version 1 (does nothing)

def createTableTask():
"""
Create a new table with the name Task
"""
#Connnection to the database and cursor creation
con = lite.connect('./exemple.sqlite')
con.row_factory = lite.Row
cur = con.cursor()
#that does nothing
try:
    cur.execute('''CREATE TABLE Tasks (\
    Name TEXT PRIMARY KEY, \
    Description TEXT, \
    Priority TEXT);''')
except lite.IntegrityError as error_SQLite:
    print("error: "+ str(error_SQLite))
else:
    print("No error has occured.")
con.close();


def insert1():
    """
    insert a new task
    """
    #Allocating variables data
    taskName = 'finish code'
    taskDescription = 'debug'
    taskPriority = 'normal'
    #Connnection to the database and cursor creation
    con = lite.connect('./exemple.sqlite')
    con.row_factory = lite.Row
    cur = con.cursor()
    #that does nothing
    try:
        with con:
            cur.execute('''INSERT INTO Tasks (Name, Description, Priority) \
            VALUES (?, ?, ?)''', (taskName, taskDescription, taskPriority))
    except lite.IntegrityError as error_SQLite:
        print("error: "+ str(error_SQLite))
    else:
        print("No error has occured. but no insert happend ?")
    con.close();

def showResult():
    """
    Show the result of the insert
    """
    con = lite.connect('./exemple.sqlite')
    con.row_factory = lite.Row
    cur = con.cursor()
    cur.execute\
    ('''SELECT * FROM Tasks ;''')
    row = cur.fetchone()
    while row:
        print(row["Name"], '  |  ', row["Description"], '  |  ', \
        row["Priority"])
        row = cur.fetchone()
    con.close();


#trying an insert version 2 (this one crash giving :Value error)
def insert2():
    """
    insert a new task
    """
    #Allocating variables data
    taskName = 'finish code'
    taskDescription = 'debug'
    taskPriority = 'normal'
    #Connnection to the database and cursor creation
    con = lite.connect('./exemple.sqlite')
    con.row_factory = lite.Row
    cur = con.cursor()
    queryInsert = ('''INSERT INTO Tasks (Name, Description, Priority) \
    VALUES (?, ?, ?)''', (taskName, taskDescription, taskPriority))
try:
    with con:
        cur.execute(queryInsert)
except lite.IntegrityError as error_SQLite:
    print("error: "+ str(error_SQLite))
else:
    print("No error has occured.")
con.close();

def run():
    createTableTask()
    insert1()
    showResult()
    insert2()
    showResult()

#calling section
run()

问题是到目前为止我所做的插入工作都没有。 第一个确实没有任何东西,只有正确的语法
第二个,它崩溃了。

这是输出:

  

spark @ spark-Razer-Blade-Pro:〜/ Documents / testing $ ./exemp.py
  没有发生错误。
  没有发生错误。但是没有发生插入?   追溯(最近的呼叫最后):
    文件" ./ exemp.py",第98行,在       的run()
    文件" ./ exemp.py",第94行,在运行中       insert2()
    文件" ./ exemp.py",第83行,在insert2中       cur.execute(queryInsert)
  ValueError:操作参数必须为str
  spark @ spark-Razer-Blade-Pro:〜/ Documents / testing $ sqlite3 exemple.sqlite
  SQLite版本3.8.2 2013-12-06 14:53:30
  输入" .help"指示
  输入以";"
终止的SQL语句   源码> SELECT * FROM Tasks;
  源码>

我正在寻找最简单的解决方案,也许我知道我的代码有什么问题。因为现在我不知道没有插入一个是怎么回事。通常它应该,或者我错过了什么?

2 个答案:

答案 0 :(得分:1)

queryInsert = ('''INSERT ...''', (taskName, taskDescription, taskPriority))

这使得queryInsert成为具有两个元素的元组 但要调用execute方法,您需要两个单独的参数。

你可以解开元组:

cur.execute(*queryInsert)

但使用两个单独的变量可能更清楚:

queryString = '''INSERT ...'''
queryParams = (taskName, taskDescription, taskPriority)

cur.execute(queryString, queryParams)

答案 1 :(得分:0)

好吧,我解决了我的错误。只是发布它,因为它可能会帮助其他人。 cur.execute()是一个寻求查询作为它的第一个参数的函数,而另一个参数是查询所需的变量。

第一步:在没有参数的情况下将查询转换为变量

queryString = ''' INSERT INTO someTables rowName, rowName2 ... VALUES (?, ?);''' 

应该有多少?因为需要变量。在这个例子中我需要2

queryValue1 = 'something'
queryValue2 = '123'

步骤2调用并执行查询:

cur.execute(queryString, queryValue1, queryValue2)

这应该没有问题