如何在python中创建一个带有1行的sqlite3数据库

时间:2018-04-22 12:49:53

标签: python python-3.x sqlite

我想知道是否有办法在python中创建一个带有单行(记录)数据的sqlite3数据库,当我再次执行代码时,它不会被制作两次。

到目前为止,我已经尝试过代码:

conn = sqlite3.connect('db_M.db')
c = conn.cursor()
no1 = "Null"
no2 = "Null"
no3 = "Null"
value = 1
try:
    c.execute("CREATE TABLE IF NOT EXISTS M_Memory(Name TEXT, Person TEXT, memory TEXT, value REAL)")
    if True:
        c.execute("INSERT INTO M_Memory(Name, Person, memory, value) VALUES (?, ?, ?, ?)",
                  (no1, no2, no3, value))
except:
    print(" foo ")
conn.commit()

2 个答案:

答案 0 :(得分:1)

我解决了我自己的问题..如果你有更好的代码分享它,请感谢你们。

import sqlite3


conn = sqlite3.connect('db_M.db')
c = conn.cursor()

c.execute("CREATE TABLE IF NOT EXISTS M_Memory(Name TEXT, Person TEXT, memory TEXT, value REAL)")


text10 = input("what do you want to call the memory ?\n")

text11 = input("what or who the memory will be about?\n")

text12 = input("what do you want me to save in it ?\n")


def Get_The_Max_Function():
    Max_Value = []
    c.execute('SELECT MAX(value) FROM M_Memory')
    lolo = c.fetchone()
    if lolo[0] is None:
        lolo = 0
        Max_Value.insert(0, lolo)
    else:
        x = int((lolo[0]))
        Max_Value.insert(0, x)
    return Max_Value


def dynamic_data_entry(Max_Value):
    Name = text10
    Person = text11
    memory = text12
    value = Max_Value[0] + 1

    c.execute("INSERT INTO M_Memory(Name, Person, memory, value) VALUES (?, ?, ?, ?)",
              (Name, Person, memory, value))
    conn.commit()


dynamic_data_entry(Get_The_Max_Function())
c.close()
conn.close()

答案 1 :(得分:0)

试试这个:

c.execute("INSERT INTO M_Memory(Name, Person, memory, value)
  SELECT ?, ?, ?, ?
  EXCEPT
  SELECT Name, Person, memory, value from M_Memory",
  (no1, no2, no3, value) )

EXCEPT,在其他数据库(例如Oracle)中为MINUS,确保如果已经存在所有值相等的另一行,则不会插入该行。