数据库的连接 进行数据的相关操作

SQLite 是一种嵌入式数据库,它的数据库就是一个文件。由于 SQLite 本身是 C 写的,而且体积很小, Python 就内置了 SQLite3 ,所以,在 Python 中使用 SQLite ,不需要安装任何东西,直接使用。

Python 定义了一套操作数据库的 API 接口,任何数据库要连接到 Python ,只需要提供符合 Python 标准的数据库驱动即可。由于 SQLite 的驱动内置在 Python 标准库中,因此可以直接来操作 SQLite 数据库。

在 Python 中操作数据库时,要先导入数据库对应的驱动,然后通过 Connection 对象和 Cursor 对象操作数据。在数据库操作完毕之后,要确保打开的 Connection 对象和 Cursor 对象都正确地被关闭,否则,资源就会泄露。


import sqlite3,os
# 连接到SQLite数据库
# 数据库文件是lhrtest.db
# 如果文件不存在,那么会自动在当前目录创建一个数据库文件:
conn = sqlite3.connect('lhrtest.db')
 
# db_file = os.path.join(os.path.dirname(__file__), 'lhrtest.db')
# if os.path.isfile(db_file):如果数据库存在
#     os.remove(db_file)
# conn = sqlite3.connect(db_file)
 
# 创建一个Cursor:
cursor = conn.cursor()
# 执行一条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\', \'xiaomaimiao\')')
# 通过rowcount获得插入的行数:
print(cursor.rowcount)
# 执行查询语句:
cursor.execute('select * from user where id=?', ('1',))
# 获得查询结果集:
values = cursor.fetchall()
print(values)
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
# 关闭Connection:
conn.close()
 
运行结果
  1.  
    1
  2.  
    [( '1', 'xiaomaimiao')]

结束后  会在文件夹下生成一个

lhrtest.db 文件

 然后用数据管理工具  进行查看数据编辑数据。

所以总的来说需要执行sql语句的时候使用 execute方法执行。

猜你喜欢

转载自www.cnblogs.com/1208xu/p/11963339.html