Python3 MySQL 数据库连接,使用 PyMySQL 连接数据库,并实现简单的增删改查。
mysql连接步骤
1.打开数据库连接
2.使用cursor()方法获取操作游标
3.执行sql和异常处理
4.关闭游标
游标常用方法
cus.cursor() 创建游标对象
cus.close() 关闭游标对象
cus.fetchone() 得到结果集的下一行
cus.fetchall() 得到结果集剩下的所有行
cus.fetchmany()
cus.execute() 执行一个数据库命令
cus.executemany(sql, args) # sql 必须是字符串类型 ,args 是一个集合
import pymysql
def connect_mysql(): # 创建一个包含connect方法参数的函数
db_config = {
'host':'127.0.0.1',
'port':3306,
'user':'citizenwang',
'password':'yourpassword',
'db':'python',
'charset':'utf8mb4' # charset 可以只写 utf8,注意不是 utf-8
}
try:
cms = pymysql.connect(**db_config) # 创建一个 pymysql 链接对象,并赋值给 变量 cms
except Exception as e:
print(e)
return cms
if __name__ == '__main__':
number = []
for i in range(1,100):
number.append(i) # 创建一个包含 1 到 99 的列表
insert_sql = 'insert into test(id) value(%s);' # 执行插入语句,将 number 插入列表
select_sql = 'select * from test;' # 选择所有的表内容
db = connect_mysql() # 创建一个 PyMySQL 数据库链接对象
cus = db.cursor() # 创建一个游标对象
try:
cus.execute('drop table if exists test; create table test(id int not null);') # 执行语句,如果存在删除,并创建
cus.executemany(insert_sql, number) # executemany(arg, para) 必须两个参数,第一个是 sql 语句,第二个是参数
cus.execute(select_sql) # execute(arg) 方法,执行
result1 = cus.fetchone() # fetchone(),选取一行内容输出
print('result1:', result1)
result2 = cus.fetchmany(4) # fetchmany(arg) 指定选取的行数
print('result2:', result2)
result3 = cus.fetchall() # fetchall() 从当前游标开始,读取所有行
print('result3:', result3)
cus.close() # 关闭游标
db.commit() # 提交数据库,如果没有这个操作,插入的数据就不会成功
except Exception as e:
db.rollback()
raise e
finally:
cus.close()