Python SQLite插入语句执行但不插入任何数据

时间:2019-01-02 15:57:49

标签: python python-3.x sqlite insert

尊敬的Stackoverflow社区,

我有以下问题。我正在使用Python 3.5 和SQLite3程序包,我正在尝试将20个城市插入数据库的城市表中。问题在于执行代码后没有错误消息,但是条目不会显示在数据库中。

我的代码如下

Database.py :此文件封装了数据库,并提供了轻松执行查询的功能。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
from sqlite3 import Error

class Database:
    database_connection = 0;

    def __init__(self, path_to_database):
        self.__try_connect__(path_to_database)

    def __try_connect__ (self, path_to_database):

        """ create a database connection to the SQLite database
        specified by the db_file
        :param db_file: database file
        :return: Connection object or None
        """
        try:
            self.database_connection = sqlite3.connect(path_to_database)
        except Error as e:
            print(e)

    def execute_query(self, query):

        database_cursor = self.database_connection.cursor()
        print(database_cursor.execute(query))

    def insert(self, table_name, assoziative_key_value_array):
        print("insert not yet implemented")

DatabaseCreator.py :如果您想尝试运行我的代码,可以使用 这个为您创建数据库的类

from Database import Database

class DatabaseCreator:
    database = 0
    @staticmethod
    def create(path_to_database):
        database = Database(path_to_database)
        DatabaseCreator.delete_old(database)
        DatabaseCreator.create_new(database)

    @staticmethod
    def delete_old(database):
        print("@DatabaseCreator - delete old")
        database.execute_query("DROP TABLE 'Städte'")
        database.execute_query("DROP TABLE 'Vereine'")
        database.execute_query("DROP TABLE 'Präsidenten'")
        database.execute_query("DROP TABLE 'Spieler'")

    @staticmethod
    def create_new(database):
        print("@DatabaseCreator - create new");
        database.execute_query("CREATE TABLE 'Städte' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL);")
        database.execute_query("CREATE TABLE 'Präsidenten' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL);")
        database.execute_query("CREATE TABLE 'Vereine' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL, 'Tabellenplatz' INTEGER NOT NULL, 'PräsidentId' INTEGER NOT NULL, 'StadtId' INTEGER NOT NULL, FOREIGN KEY('StadtId') REFERENCES 'Städte'('Id'), FOREIGN KEY('PräsidentId') REFERENCES 'Präsidenten'('Id') ,CONSTRAINT exclusive_präsidentschaft UNIQUE ('PräsidentId'));")
        database.execute_query("CREATE TABLE 'Spieler' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL, 'Alter' INTEGER NOT NULL, 'Position' Varchar NOT NULL, 'VereinId' INTEGER NOT NULL, FOREIGN KEY('VereinId') REFERENCES 'Vereine'('Id'));")

DatabaseSeeder.py :此类在其静态方法中使用Database类,并尝试插入 数据库中的20个城市。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Database import Database


class DatabaseSeeder:

    database = 0

    @staticmethod
    def seed(database):
        DatabaseSeeder.seed_cities(database)
        DatabaseSeeder.seed_presidents(database)
        DatabaseSeeder.seed_clubs(database)
        DatabaseSeeder.seed_players(database)

    @staticmethod
    def seed_cities(database):
        print("@DatabaseSeeder - seed cities")
        cities = [
            "Berlin",
            "Hamburg",
            "München",
            "Köln",
            "Frankfurt am Main",
            "Stuttgart",
            "Düsseldorf",
            "Dortmund",
            "Essen",
            "Leipzig",
            "Bremen",
            "Dresden",
            "Hannover",
            "Nürnberg",
            "Duisburg",
            "Bochum",
            "Wuppertal",
            "Bielefeld",
            "Bonn",
            "Münster"
        ]

        insert_city_sql_template = "INSERT INTO 'Städte' ('{0}') VALUES ('{1}');"
        for city in cities:
            sql_query = insert_city_sql_template.format("Name", city)
            print(sql_query)
            database.execute_query(sql_query)

我用于创建最终sql语句的模板如下

insert_city_sql_template = "INSERT INTO 'Städte' ('{0}') VALUES ('{1}');"

在这里将其格式化为最终的sql语句

sql_query = insert_city_sql_template.format("Name", city)

当我在执行之前打印sql语句时,它看起来像这样

INSERT INTO 'Städte' ('Name') VALUES ('Berlin');


Application.py :在我的主类中,我首先创建了一个新的数据库连接,并将此连接移交给DatabaseSeeder类。

from tkinter import *
import sqlite3
from sqlite3 import Error
from Database import Database
from table import Table
from DatabaseCreator import DatabaseCreator
from DatabaseSeeder import DatabaseSeeder

def main():
    database_path = "./database.db"
    DatabaseCreator.create(database_path)
    database = Database(database_path)
    DatabaseSeeder.seed(database)

执行代码时,我没有收到任何错误消息 但是条目将不会显示在数据库中。 enter image description here

当我从代码中复制SQL语句并直接在sqlite cli上执行时,它运行得很好。

enter image description here

我希望你们中的某人知道我所缺少的。非常感谢:)

1 个答案:

答案 0 :(得分:1)

好吧,感谢@stovfl,我找到了解决方案。我确实错过了commit语句。现在,我的execute_query方法看起来像这样,最后是 commit

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FirebaseMessaging.getInstance().subscribeToTopic("News");
}

非常感谢您的帮助,并始终记得进行更改:D

问候