首页 文章

Python3和Sqlite3无法插入

提问于
浏览
0

我正在尝试编写一个函数来做一个简单的插入 . 这是我到目前为止所尝试的

#! /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 version 3.8.2 2013-12-06 14: 53:30输入“.help”作为指令输入以“;”结尾的SQL语句sqlite> SELECT * FROM Tasks; sqlite的>

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

2 回答

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

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

    你可以解压缩元组:

    cur.execute(*queryInsert)
    

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

    queryString = '''INSERT ...'''
    queryParams = (taskName, taskDescription, taskPriority)
    
    cur.execute(queryString, queryParams)
    
  • 0

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

    第一步:将查询变为没有参数的变量

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

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

    queryValue1 = 'something'
    queryValue2 = '123'
    

    第2步调用并执行查询:

    cur.execute(queryString, queryValue1, queryValue2)
    

    这应该没有问题

相关问题