Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

sqlite - Database locked-error - problem with sqlite3 and python

I'm having some trouble adding information to a data base. The problem I get is that my code console says "OperationalError". Does anyone have an idea on how to solve this? My code looks as follow:

import sqlite3


def add_data(cursor):
    a         = input("Insert 'a':")
    b         = input("Insert b:")
    c        = input("Insert c:")
    d        = input("Insert d:")
   
    expression=f'INSERT INTO data VALUES ( {a}, {b}, {c}, {d});'
    cursor.execute(expression)

def main(db_file):
    con, cur = get_connection(db_file)
    adddata = add_data(cur)

        print(row)
main('data.db')
question from:https://stackoverflow.com/questions/65888953/database-locked-error-problem-with-sqlite3-and-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can convert the current code to this one :

...
def add_data(cursor):
    id       = input("Insert 'id':")
    abbrev   = input("Insert abbrev:")
    latin    = input("Insert latin:")
    common   = input("Insert common:")
   
    expression=f'INSERT INTO species VALUES (?,?,?,?)'
    cursor.execute(expression,(id,abbrev,latin,common,))

def main(db_file):
    con, cur = get_connection(db_file)
    adddata = add_data(cur)
    con.commit()    

main('data.db')

where

  • the redundant for cursor is removed
  • the DML statement is committed
  • the placeholders for variables should be converted to the question marks, rather than explicit variable names, as being securer, while creating a parameter list as a tuple with four elements within the execute function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...