如何使用 Python 将值直接插入到 SQL base table 中?
How to insert values directly into SQL base table using Python?
我正在尝试通过 python 建立连接获取用户输入,从而在 SQL table 中添加值。
我已尝试与 SQL 数据库建立连接并在 table 中添加值,但这些值只是暂时添加到 python 中,并且不会插入到 python 中SQLtable
我尝试了以下方法:
database ='c:\sqlite\db\chinook.db'
conn =sqlite3.connect(database)
cur =conn.cursor()
sql ="Insert into books(id,title,author,genre,owner) values (?,?,?,?,?) "
value1 =(2,'Outliers','Malcom Gladwell','Non-Fiction','Ishant Sahu')
cur.execute(sql,value1)
sql2 ="Select * from books; "
db = pd.read_sql(sql2,conn)
我可以看到数据库中插入的值:
id title author genre owner
1 Shoe Dog Phil Knight Memoir Jitesh Singla
2 Outliers Malcom Gladwell Non-Fiction Ishant Sahu
但是当我在 SQL 服务器上 运行 table 时,没有任何变化:
1 Shoe Dog Phil Knight Memoir Jitesh Singla
有没有办法做到这一点,如果没有,为什么这不可能?
在python个数据库连接中,默认自动提交是false。因此您需要提交查询以将数据保存到数据库中。
# 导入SQLite驱动:
import sqlite3
# 连接到SQLite数据库
# 数据库文件是test.db
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('samples/sample.db')
# 创建一个Cursor:
cursor = conn.cursor()
if __name__ != '__main__':
# 执行一条SQL语句,创建user表:
cursor.execute('CREATE TABLE user(id VARCHAR(20) PRIMARY KEY,name VARCHAR(20))')
# 继续执行一条SQL语句,插入一条记录:
cursor.execute("INSERT INTO user(id,name) VALUES ('1','Michael')")
# 通过rowcount获得插入的行数:
print(cursor.rowcount)
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
# 关闭Connection:
conn.close()
记住conn.commit()。
我正在尝试通过 python 建立连接获取用户输入,从而在 SQL table 中添加值。
我已尝试与 SQL 数据库建立连接并在 table 中添加值,但这些值只是暂时添加到 python 中,并且不会插入到 python 中SQLtable
我尝试了以下方法:
database ='c:\sqlite\db\chinook.db'
conn =sqlite3.connect(database)
cur =conn.cursor()
sql ="Insert into books(id,title,author,genre,owner) values (?,?,?,?,?) "
value1 =(2,'Outliers','Malcom Gladwell','Non-Fiction','Ishant Sahu')
cur.execute(sql,value1)
sql2 ="Select * from books; "
db = pd.read_sql(sql2,conn)
我可以看到数据库中插入的值:
id title author genre owner
1 Shoe Dog Phil Knight Memoir Jitesh Singla
2 Outliers Malcom Gladwell Non-Fiction Ishant Sahu
但是当我在 SQL 服务器上 运行 table 时,没有任何变化:
1 Shoe Dog Phil Knight Memoir Jitesh Singla
有没有办法做到这一点,如果没有,为什么这不可能?
在python个数据库连接中,默认自动提交是false。因此您需要提交查询以将数据保存到数据库中。
# 导入SQLite驱动:
import sqlite3
# 连接到SQLite数据库
# 数据库文件是test.db
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('samples/sample.db')
# 创建一个Cursor:
cursor = conn.cursor()
if __name__ != '__main__':
# 执行一条SQL语句,创建user表:
cursor.execute('CREATE TABLE user(id VARCHAR(20) PRIMARY KEY,name VARCHAR(20))')
# 继续执行一条SQL语句,插入一条记录:
cursor.execute("INSERT INTO user(id,name) VALUES ('1','Michael')")
# 通过rowcount获得插入的行数:
print(cursor.rowcount)
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
# 关闭Connection:
conn.close()
记住conn.commit()。