python操作数据库
1.python中的两个对象
1.连接对象 connection
作用:创建一个python程序到数据库的 连接通道 和jdbc连接是一个道理
方法:
cursor 创建游标
commit 提交事务
rollback 事务回滚
参数:
1.mysql服务器地址 IP
2.端口号 port 3306
用户名 user root
密码 password root
数据库 database test
字符集 charset
2.游标对象 cursor
是操作数据库的一个指针,类似于 在高速路上的大货车,从起点 建立连接到终点 关闭连接
常用方法:
execute(sql) 执行sql命令的一个方法
fetchone 取出结果集的下一行
fetchmany(size) 取出结果集的下几行
fechall 获取结果集的所有行
rowcount 最近一次执行execute 返回结果集的行数或者影响的行数
close 关闭
操作 sqlite 流程
sqlite操作流程:
1.导入模块sqlite import sqlite3
2.创建连接对象connection conn = sqlite3.connect('mrsoft.db')
3.创建游标对象cursor cursor = conn.cursor()
4.执行sql语句 cursor.execute('create table user(id int(10), primary key name varchar(20))')
5.关闭游标对象 cursor.close()
6.关闭连接对象 conn.close()
5.操作mysql数据库
a.安装mysql数据库
b.配置环境变量
c.开启服务连接测试
d.使用Navicat连接mysql
e.使用pip命令安装pymysql模块
连接数据库的流程:
# 导入模块pymysql
import pymysql
# 打开数据库,参数1:主机名域IP 参数2:用户名 参数3:密码 参数4:数据库名称
db = pymysql.connect('localhost', 'root', 'root', 'stuypython')
# 使用cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用execute() 方法执行sql查询
cursor.execute('SELECT VARSION()') # 如果表存在删除表 'DROP TABLE IF EXISTS 表名'
# 使用fetchone() 方法取单条数据
data = cursor.fetchone()
print('Database version : %s' % data)
# 关闭游标
cursor.close()
# 关闭数据库连接
db.close()
创建表
import pymysql
db = pymysql.connect('localhost', 'root', 'root', 'mrsoft')
cursor = db.cursor()
# 如果表存在删除表
cursor.execute('DROP TABLE IF EXISTS books')
print('books已删除')
sql = '''
create table books(
id int(8) primary key,
name varchar(20) not null,
category varchar(20) not null,
price decimal(10, 2),
publish_time date
)
'''
cursor.execute(sql)
cursor.close()
db.close()
插入数据
import pymysql