我是靠谱客的博主 天真耳机,最近开发中收集的这篇文章主要介绍python-操作DB,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

python --mysql

python3: pymysql
python2: MySQLdb

步骤:
1,  建立数据库连接对象
    db = pymysql.connect("dbaddress","username","password","dbname",charset = "utf8")
    
2, 创建游标对象
    cursor = db.cursor()
3, 使用游标对象的方法操作数据库
    cursor.execute("command;");
4, 提交commit
    db.commit();
5, 关闭游标对象
    cursor.close()
6, 关闭数据库连接
    db.close();
    
    
db连接对象支持的方法:
1, cursor() 创建游标对象
2, commit() 提交方法
3, rollback()回滚方法
4,close() 关闭连接    

cursor对象支持的方法:
1, execute("SQL命令") 执行SQL命令
2, fetchone() 取得结果集的第一条记录
3,fetchmany(n)取得结果集的n条记录        
4, fetchall()取得结果集的所有记录
5, close() 关闭游标对象

import pymysql
# python操作mysql 步骤:
# 1, 建立数据库连接
# 2, 创建游标对象
# 3, 使用游标对象的方法操作数据库
# 4, 提交commit
# 5, 关闭游标对象
# 6, 关闭数据库连接
try:
#创建db连接对象
db = pymysql.connect("192.168.10.16","wang","123456","wang",charset = "utf8")
#创建游标对象
cursor = db.cursor()
#cursor.execute("create database wang;")
#如果连接的时候未指定库名,则必须use db
cursor.execute("use wang;")
#执行语句
# sql_create = "create table t3(id int auto_increment, name varchar(30) default '', age int default 0, score int default 0,primary key(id))engine = innodb;"
# cursor.execute(sql_create)
sql_insert = "insert into t3(name,age,score) values('llj',20,100),('wanghuan',18,99);"
cursor.execute(sql_insert)
#查询语句
sql_query = "select * from wang.t3 limit 5;"
#执行查询语句;执行后,结果集保存在cursor中
cursor.execute(sql_query)
# 将结果集赋值给变量,并打印
data = cursor.fetchall()
print("查询结果集为:")
for I in data:
print(I)
#事物操作,必须要提交,也可以rollback()
db.commit()
finally:
#关闭连接
cursor.close()
db.close()
import pymysql
host = "192.168.10.16"
user = "wang"
password = "123456"
dbname = "wang"
ch = "utf8"
db = pymysql.connect(host, user, password, dbname, charset = ch)
cur = db.cursor()
try:
sql_update_1 = "update t3 set age = age + 1 where name = 'llj';"
sql_update_2 = "update t3 set age = age + 2 where name = 'wanghuan';"
cur.execute(sql_update_1)
cur.execute(sql_update_2)
db.commit()
print("execute successfully;")
except Exception as e:
db.rollback()
print("execute failed, command has been rollback")
cur.close()
db.close()

 

最后

以上就是天真耳机为你收集整理的python-操作DB的全部内容,希望文章能够帮你解决python-操作DB所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部