import sqlite3 as sql
import os
db_folder = "D:/Python/databases/accounts.sqlite"
db = sql.connect(db_folder)
im = sql.Cursor()
im.execute("""CREATE TABLE IF NOT EXISTS 'accounts' (
id TEXT DEFAULT 'account' UNIQUE
pw TEXT DEFAULT 'password
email TEXT UNIQUE
)
""")
datas = [
("eren.arc1","1236"),
("ern.arc"),
(none,none,"erenarici@gmail.com")
]
if not os.path.exists(db_folder):
for data in datas :
im.execute("""INSERT INTO 'accounts' VALUES (?,?,?)""",datas)
db.commit()
我运行了这段代码,我收到了这个错误:
File "databases/db4.py", line 6, in <module>
im = sql.Cursor()
TypeError: function takes exactly 1 argument (0 given)
有什么问题?我没有经常在光标函数中看到参数。
注意:我使用了cursor()
但是我接受了sqlite3没有得到游标属性错误。然后我将其更改为Cursor()
。
答案 0 :(得分:2)
执行:
import sqlite3 as sql
import os
sqlite_file = "db.sqlite"
conn = sql.connect(sqlite_file)
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS accounts (
id TEXT DEFAULT 'account' UNIQUE,
pw TEXT DEFAULT 'password',
email TEXT UNIQUE);""")
items = [
("id1", "pw1", "user1@gmail.com"),
("id2", "pw2", "user2@gmail.com"),
("id3", "pw3", "user3@gmail.com")
]
for item in items:
c.execute("""INSERT INTO accounts VALUES (?,?,?);""", item)
c.execute("""INSERT INTO accounts(id, email) VALUES ('id4', 'user4@gmail.com');""")
c.execute("""INSERT INTO accounts(email) VALUES ('account@gmail.com');""")
for row in c.execute('SELECT * FROM accounts'):
print(row)
conn.commit()
conn.close()
输出:
('id1', 'pw1', 'user1@gmail.com')
('id2', 'pw2', 'user2@gmail.com')
('id3', 'pw3', 'user3@gmail.com')
('id4', 'password', 'user4@gmail.com')
('account', 'password', 'account@gmail.com')
如果您尊重每个字段的顺序,您可以检查item
元组的长度以在循环中执行插入:
for item in items:
if len(item) == 3:
c.execute("""INSERT INTO accounts VALUES (?,?,?);""", item)
elif len(item) == 2:
c.execute("""INSERT INTO accounts(pw, email) VALUES (?,?);""", item)
elif len(item) == 1:
c.execute("""INSERT INTO accounts(email) VALUES (?);""", item)
但是(none, none, 'email')
在这里没有意义,使用关键字NULL
插入NULL数据(如果python是None
而不是none
)。