文章目录
操作 SQLite3数据库创建表插入数据插入一条数据插入多条数据
查询数据查询所有数据查询一条数据
删除数据删除数据库
简单的sqllite 语法- 文档查询
操作 SQLite3数据库
导入相关库或模块(SQLite3)。使用connect()连接数据库并获取数据库连接对象。它提供了以下方法:
.cursor() 方法来创建一个游标对象.commit() 方法来处理事务提交.rollback() 方法来处理事务回滚.close() 方法来关闭一个数据库连接
使用con.cursor()获取游标对象。使用游标对象的方法(execute()、executemany()、fetchall()等)来操作数据库,实现插入、修改和删除操作,并查询获取显示相关的记录。在Python程序中,连接函数sqlite3.connect()有如下两个常用参数。
database:表示要访问的数据库名。timeout:表示访问数据的超时设定。
使用close()关闭游标对象和数据库连接。数据库操作完成之后,必须及时调用其close()方法关闭数据库连接,这样做的目的是减轻数据库服务器的压力。
创建表
import sqlite3
con
= sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
= con
.cursor
()
sql
= 'create table t_person(pno INTEGER PRIMARY KEY AUTOINCREMENT ,pname varchar(30) NOT NULL ,age INTEGER)'
try:
cur
.execute
(sql
)
except Exception
as e
:
print(e
)
print('创建表失败')
finally:
cur
.close
()
con
.close
()
插入数据
插入一条数据
import sqlite3
con
=sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
=con
.cursor
()
sql
='insert into t_person(pname,age) values(?,?)'
try:
cur
.execute
(sql
, ('张三', 24))
con
.commit
()
print('插入数据成功')
except Exception
as e
:
print(e
)
con
.rollback
()
print('插入数据失败')
finally:
cur
.close
()
con
.close
()
插入多条数据
import sqlite3
con
=sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
=con
.cursor
()
sql
='insert into t_person(pname,age) values(?,?)'
try:
cur
.executemany
(sql
,[('小李',23),('小花',34),('小明',28)])
con
.commit
()
print('插入多条数据成功')
except Exception
as e
:
print(e
)
con
.rollback
()
print('插入多条数据失败')
finally:
cur
.close
()
con
.close
()
查询数据
查询所有数据
import sqlite3
con
=sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
=con
.cursor
()
sql
='select * from t_person'
try:
cur
.execute
(sql
)
person_all
=cur
.fetchall
()
for person
in person_all
:
print(person
)
except Exception
as e
:
print(e
)
print('查询所有数据失败')
finally:
cur
.close
()
con
.close
()
查询一条数据
import sqlite3
con
=sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
=con
.cursor
()
sql
='select * from t_person'
try:
cur
.execute
(sql
)
person_all
=cur
.fetchone
()
for person
in person_all
:
print(person
)
except Exception
as e
:
print(e
)
print('查询所有数据失败')
finally:
cur
.close
()
con
.close
()
删除数据
import sqlite3
con
=sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
=con
.cursor
()
sql
='delete from t_person where pno=?'
try:
cur
.execute
(sql
, (2,))
con
.commit
()
print('删除成功')
except Exception
as e
:
print(e
)
print('删除失败')
con
.rollback
()
finally:
con
.close
()
删除数据库
import sqlite3
con
=sqlite3
.connect
('D:/Python/StudyPython/Jupyter/数据库编程/sqlitedb/first.db')
cur
=con
.cursor
()
sql
='delete from t_person where pno=?'
try:
cur
.execute
(sql
, (2,))
con
.commit
()
print('删除成功')
except Exception
as e
:
print(e
)
print('删除失败')
con
.rollback
()
finally:
con
.close
()