美文网首页
Python3.7 MySQL 数据库连接

Python3.7 MySQL 数据库连接

作者: Demon_半夏 | 来源:发表于2019-07-15 17:05 被阅读0次

一、安装MySQLdb

PyMySQL 是在Python3.x 版本中用于连接 MySQL 服务器的一个库
① 可以直接pip安装:pip install PyMySQL


② Git下载地址:PyMySQL
解压下载文件,不用打开python交互界面,CMD到解压文件所在目录
运行 python setup.py install

二、连接MySQL数据库

#导入pymysql的包
import pymysql

try:
#获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
    conn=pymysql.connect(host='服务器地址',port=端口号,user='用户名',passwd='密码',db='数据库名称',charset='连接编码')
    # 使用cursor()方法创建一个游标对象
    cur = conn.cursor()
    # 使用execute()方法执行SQL查询
    cur.execute('SELECT VERSION()')
    data = cur.fetchone()
    for d in data:
        # 注意int类型需要使用str函数转义
        print('database version: %s' % data)

    cur.close()  # 关闭游标
    conn.close()  # 释放数据库资源
except  Exception: print("发生异常")

运行上面代码,显示:database version: 5.7.26,表示连接成功

三、参数说明

pymysql.Connect()参数说明
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
passwd(str): 密码
db(str): 数据库名称
charset(str): 连接编码

connection对象支持的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接

cursor对象支持的方法
execute(op) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchall() 获取结果集中的所有行
rowcount() 返回数据条数或影响行数
close() 关闭游标对象

四、例句

1、select操作
import pymysql

# 打开数据库连接
db = pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')


# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 查询语句
# sql = "SELECT * FROM tb_verify_code \
#         WHERE phone = '%s' "
# sql查询数据库时间最新的一条记录
sql = "SELECT * FROM tb_verify_code \
      WHERE phone ='%s' \
      ORDER BY id DESC LIMIT 0,1  "
data = ('18573961234',)
cursor.execute(sql % data)
try:
    # 执行SQL语句
    cursor.execute(sql % data)
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        phone = row[1]
        code = row[2]
        type = row[3]
        # 打印结果
        print("phone=%s,code=%s,type=%s" % \
              (phone,code,type))
except:
    print("Error: unable to fetch data")

# 关闭数据库连接
db.close()
2、insert操作
import pymysql
db= pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
 
# 使用cursor()方法获取操作游标
cur = db.cursor()
 
sql_insert ="""insert into user(id,username,password) values(4,'张三','123456')"""
 
try:
    cur.execute(sql_insert)
    #提交
    db.commit()
except Exception as e:
    #错误回滚
    db.rollback() 
finally:
    db.close()
3、update操作
import pymysql

db=  pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
 
# 使用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()
4、delete操作
import pymysql
db=  pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
 
# 使用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()

相关文章

网友评论

      本文标题:Python3.7 MySQL 数据库连接

      本文链接:https://www.haomeiwen.com/subject/idbnkctx.html