作为一个Python初学者,我想通过写博客的方式来记录下来自己成长的过程,同时也分享一下自己学习到的知识。以下都是一个Python初学者对Python语言的一些浅见和个人理解。
'''
1.导入sqlite3模块
2.创建连接sqlite3.connect()
3.创建游标对象
4.编写创建表的sql语句
5.执行sql
6.关闭连接
'''
import sqlite3
# 创建连接
con = sqlite3.connect('f:\Python\sqlite3Demo/demo.db')
print(con)
# 创建游标对象
cur = con.cursor()
# 编写创建表的sql语句
sql = '''create table t_person(
pno INTEGER primary key autoincrement,
pname VARCHAR not null,
age INTEGER
)'''
try:
# 执行sql语句
cur.execute(sql)
print('创建表成功')
except Exception as e:
print(e)
print('创建表失败')
finally:
# 关闭游标
cur.close()
# 关闭连接
con.close()
# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect('f:\Python\sqlite3Demo/demo.db')
# 创建游标对象
cur = con.cursor()
# 编写插入sql
sql = 'insert into t_person(pname,age) values(?,?)'
try:
# 执行sql
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('f:\Python\sqlite3Demo/demo.db')
# 创建游标
cur = con.cursor()
# 编写插入sql
sql = 'insert into t_person(pname,age) values(?,?)'
try:
# 执行sql
cur.executemany(sql,[('张三',23),('李四',24)])
# 提交事务
con.commit()
print('插入多条数据成功')
except Exception as e:
print(e)
con.rollback()
print('插入多条数据失败')
finally:
# 关闭游标连接
cur.close()
# 关闭事务连接
con.close()
# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect('f:\Python\sqlite3Demo/demo.db')
# 创建游标
cur = con.cursor()
# 创建查询sql
sql = 'select * from t_person'
try:
cur.execute(sql)
# 获取结果集
person_all = cur.fetchall()
# print(person_all)
for person in person_all:
print(person)
except Exception as e:
print(e)
print('查询所有数据失败')
finally:
# 关闭游标
cur.close()
# 关闭连接
con.close()
# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect('f:\Python\sqlite3Demo/demo.db')
# 创建游标
cur = con.cursor()
# 创建查询sql
sql = 'select * from t_person'
try:
cur.execute(sql)
# 获取结果集
person = cur.fetchone()
print(person)
except Exception as e:
print(e)
print('查询数据失败')
finally:
# 关闭游标
cur.close()
# 关闭连接
con.close()
# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect('f:\Python\sqlite3Demo/demo.db')
# 创建游标
cur = con.cursor()
# 编写修改的SQL语句
sql = 'update t_person set pname=? where pno=?'
# 执行sql
try:
cur.execute(sql,('张三',1))
print('修改成功')
except Exception as e:
print(e)
print('修改失败')
con.rollback()
finally:
# 关闭游标
cur.close()
# 关闭连接
con.close()
# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect('f:\Python\sqlite3Demo/demo.db')
# 创建游标
cur = con.cursor()
# 编写删除的SQL语句
sql = 'delete from t_person where pno=?'
# 执行sql
try:
cur.execute(sql,(1,))
# 提交事务
con.commit()
print('删除成功')
except Exception as e:
print(e)
print('删除失败')
con.rollback()
finally:
# 关闭游标
cur.close()
# 关闭连接
con.close()