python sqlite3插入表错误:游标未连接?

时间:2017-10-28 16:18:15

标签: python mysql sqlite insert

我尝试使用IPopUp将数据导入AWS RDS数据库中的表sqlite3。对于我尝试的两种方法,第一个babyName每次都正常工作,但第二个data_entry()给了我

  

光标未连接

  

并非所有参数都被使用

错误。你能帮我吗?

new_data_entry()

我不断收到的错误消息:

import mysql.connector
from mysql.connector import errorcode

# start connection
try:
    cnn = mysql.connector.connect(
    user = '*****',
    password = '*****',
    host = '*****-mysql.*****.us-****-1.rds.amazonaws.com',
    database = '*******')
    print('It works!')
except mysql.connector.Error as e:
    if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('Somethign is wrong with username or password')
    elif e.errno == errorcode.ER_BAD_DB_ERROR:
        print('Database does not exist')
    else:
        print(e)

# start cursor
import sqlite3
c = cnn.cursor()
def creat_table():
    c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
    c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
    cnn.commit()
    c.close()
    cnn.close()

def new_data_entry():
    name = 'Wendy'
    gender = 'F'
    frequency = 321
    year = '2006'
    c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
    cnn.commit()
    c.close()
    cnn.close()

# creat_table()
data_entry()
print('It works!')
new_data_entry()

2 个答案:

答案 0 :(得分:0)

select t.row,t.name (case when t.priority = 1 then t.cost else ' ' end ) as Priority1, (case when t.priority = 2 then t.cost else ' ' end ) as Priority2, (case when t.priority = 3 then t.cost else ' ' end ) as Priority3, (case when t.priority = 4 then t.cost else ' ' end ) as Priority4 From (select Row,name,priority,cost from Table2 group by name) t group by t.name; 结束时,您已关闭与数据库data_entry的连接,该数据库在全局范围内保存为变量。当您尝试运行cnn时,连接已经关闭,这就是错误。

相反,请保持连接处于打开状态。

new_data_entry

答案 1 :(得分:0)

我解决了问题!

def new_data_entry():
    name = 'Wendy'
    gender = 'F'
    frequency = 321
    year = '2006'
    c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (%s, %s, %s, %s)", (name, gender, frequency, year))
    cnn.commit()

def finish():
    c.close()
    cnn.close()

更改所有“?”到“%s”,代码全部贯穿〜谢谢你们!