python笔记----python 操作数据库
1.数据库编程接口
1.1连接对象
connect()函数 ————生成Connection对象
Connection对象的方法:
cursor()获取游标对象,操作数据库
commit() 提交事务
rollback()回滚事务
close()关闭数据库连接
1.2 游标对象
由Connection对象 生成cursor 对象
1.3 使用SQLite
1.数据库的基础知识::存储数据
非常重要的对象,数据表,一系列二维数组组成
2.流程
2.1 连季数据库
2.2 执行SQL语句
2.3 关闭连接
3.创建数据库文件
步骤:
1.导入sqlite3模块
2.创建Connection连接对象
3.创建Cursor游标对象
4.执行SQL语句
5.关闭游标
6. 关闭连接
例子:
import sqlite3
conn = sqlite3.connect(‘mrsoft.db’)
cursor = conn.cursor()
cursor.execute(‘create table user(id int(10) primary key,name varchar(20)’)
cursor.close()
conn.close()
4.操作SQLite数据
1.新增
2.删除
3.修改
4.查询
例子:
import sqlite3
conn = sqlite3.connect(‘mrsoft.db’)
cursor = conn.cursor()
sql = ‘insert into user (id , name) values(1,“mrsoft”)’
cursor.execute(sql)
cursor.close()
#提交事务
conn.commit()
conn.close()
1.5 下载MySQL
地址:https://dev.mysql.com/downloads/windows/installer/5.7.html
下载navicat for MySQL
地址: https://www.navicat.com/en/products/navicat-for-mysql
下载pymysql
pip install PyMysql
说明文档地址:https://pymysql.readthedocs.io/en/latest/
1.连接数据库
import pymysql
db = pymysql.connect(‘host’,‘root’,‘password’,‘database’)
cursor = db.cursor()
cur.excute(‘select version()’) #查看版本号
data = cursor.fetchone() #查询数据
cursor.close()
db.close()
2.创建数据表
import pymysql
db = pymysql.connect(‘host’,‘root’,‘password’,‘database’)
cursor = db.cursor()
cursor.excute(‘drop table if exists books’) #如果表存在就删除,没有就继续创建
sql = ‘’’
CREATE TABLE books(
id int(8) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
category varchar(50) NOT NULL,
…
PRIMARY KEY (id)
)ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET =utf8;
‘’’
cursor.excute(sql) #
cursor.close()
db.close()
3.操作MySQLite数据表