python操作mysql的方法-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

专注于为中小企业提供成都网站建设、做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业阳东免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千余家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

这篇文章主要介绍python操作mysql的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x,而MySQLdb不支持3.x版本。

本文测试python版本:3.6。mysql版本:5.6.24

1.通过 pip 安装 pymysql

进入cmd,输入:

pip install pymysql

按回车键,等待安装完成。

python操作mysql的方法

2.测试连接

import pymysql  #导入 pymysql ,如果编译未出错,即表示 pymysql 安装成功

3.pymysql操作

表结构如下:

python操作mysql的方法

3.1查询操作

import pymysql  #导入 pymysql
#打开数据库连接
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法获取操作游标
cur = db.cursor()
#1.查询操作
# 编写sql 查询语句  user 对应我的表名
sql = "select * from user"
try:
    cur.execute(sql)     #执行sql语句
    results = cur.fetchall()    #获取查询的所有记录
    print("id","name","password")
    #遍历结果
    for row in results :
        id = row[0]
        name = row[1]
        password = row[2]
        print(id,name,password)
except Exception as e:
    raise e
finally:
    db.close()    #关闭连接

3.2插入操作

import pymysql
#2.插入操作
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""
try:
    cur.execute(sql_insert)
    #提交
    db.commit()
except Exception as e:
    #错误回滚
    db.rollback() 
finally:
    db.close()

3.3更新操作

#3.更新操作
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql_update ="update user set username = '%s' where id = %d"
try:
    cur.execute(sql_update % ("xiongda",3))  #像sql语句传递参数
    #提交
    db.commit()
except Exception as e:
    #错误回滚
    db.rollback() 
finally:
    db.close()

3.4删除操作

import pymysql
#4.删除操作
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法获取操作游标
cur = db.cursor()
sql_delete ="delete from user where id = %d"
try:
    cur.execute(sql_delete % (3))  #像sql语句传递参数
    #提交
    db.commit()
except Exception as e:
    #错误回滚
    db.rollback() 
finally:
    db.close()

以上是python操作mysql的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联-成都网站建设公司行业资讯频道!


网站题目:python操作mysql的方法-创新互联
文章路径:http://myzitong.com/article/dipedh.html