十四、数据库编程

一、操作SQLite3数据库

    从Python3.x版本开始,在标准库中已经内置了SQLlite3模块,它可以支持SQLite3数据库的访问和相关的数据库操作。在需要操作SQLite3数据库数据时,只须在程序中导入SQLite3模块即可。

1)例子

#操作sqlite3创建表
#1.导入模块
#2.创建连接对象
#3.创建游标,用于执行语句
#4.创建表语句,使用'''''',表示文本对象
#5.执行sql语句
#6.关闭连接close
import sqlite3
conn = sqlite3.connect("d:/py_sqlite3/sql01.sql")
cur =conn.cursor()
sql = '''create table t_person(
pid integer primary key autoincrement,
pname varchar not null,
age INTEGER
)'''
try:
cur.execute(sql)
print("执行成功")
except Exception as e:
print(e)
print("创建失败")
finally:
cur.close()
conn.close()
2)例子
'''
表中插入一条,多条数据
execute\executemany
修改/删除同代码。使用execute即可
'''
#导入模块
import sqlite3
# 建立连接对象
conn = sqlite3.connect("d:/py_sqlite3/sql01.sql")
#创建游标对象,用于执行sql
cur = conn.cursor()
#插入sql
sql = 'insert into t_person(pname,age) values(?,?)'
try:
# 执行插入
# cur.execute(sql,('张三',24))
# cur.executemany(sql,[('李四',24),('王五',22),('赵六',27)])
print("操作成功")
conn.commit()
except Exception as e:
print(e)
print("操作失败")
conn.rollback()
finally:
cur.close()
conn.close()
3)例子
'''
查询一条或者多条数据
fetchall/fetchone
'''
#导入模块
import sqlite3
#建立连接
conn = sqlite3.connect("d:/py_sqlite3/sql01.sql")
#建立游标,用于执行sql
cur = conn.cursor()
#建立sql
sql = 'select *from t_person'
#执行语句
try:
cur.execute(sql)
#1)返回结果集fetchall
#person_all = cur.fetchall()
#遍历结果集
#for person in person_all:
# print(person)
#2)返回一个结果fetchone
person = cur.fetchone()
print(person)
except Exception as e:
print(e)
print('执行失败')
finally:
cur.close()
conn.close()





猜你喜欢

转载自www.cnblogs.com/dangjingwei/p/12318476.html