当前位置:首页 > 原创教程 > Python连接MySQL数据库并读写数据库

Python连接MySQL数据库并读写数据库

原创教程 / 星之宇 / 2023-2-20 21:44 / 浏览:1604 / 评论:0

本文主要介绍Python连接MySQL数据库并读写数据库。


一、安装PyMySql库

使用命令: pip install pymysql

339-1.png


二、连接测试

获取数据库版本。

import pymysql
 
# 打开数据库连接
db = pymysql.connect(
         host='数据库地址',
         port=数据库端口,
         user='数据库账号',
         passwd='数据库密码',
         db='数据库名称',
         charset='utf8'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

339-2.png


三、数据库操作

1、查询操作

import pymysql
 
# 打开数据库连接
db = pymysql.connect(
         host='77bx.com',
         port=3306,
         user='77bx.com',
         passwd='77bx.com',
         db='77bx.com',
         charset='utf8'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 查询语句
sql = "SELECT * FROM xzy_user WHERE id < %s" % (1000)

try:
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute(sql)

    # 使用 fetchall() 方法获取所有记录列表.
    data = cursor.fetchall()
    for row in data:
        print(row)
except:
    print("Error: cannot fetch data");
 
# 关闭数据库连接
db.close()


2、更新操作

import pymysql
 
# 打开数据库连接
db = pymysql.connect(
         host='77bx.com',
         port=3306,
         user='77bx.com',
         passwd='77bx.com',
         db='77bx.com',
         charset='utf8'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 更新语句
sql = "UPDATE xzy_user SET username = '%s' WHERE id = '%s'" % ('77bx',1000)

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()


3、插入操作

import pymysql
 
# 打开数据库连接
db = pymysql.connect(
         host='77bx.com',
         port=3306,
         user='77bx.com',
         passwd='77bx.com',
         db='77bx.com',
         charset='utf8'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 插入语句
sql = "INSERT INTO xzy_user(username, password, status) VALUES ('%s', '%s',  '%s')" % ('77bx', '77bx','vip')

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()


4、删除操作

import pymysql
 
# 打开数据库连接
db = pymysql.connect(
         host='77bx.com',
         port=3306,
         user='77bx.com',
         passwd='77bx.com',
         db='77bx.com',
         charset='utf8'
         )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 删除语句
sql = "DELETE FROM xzy_user WHERE username = '%s'" % ('77bx')

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

目前有 0 条评论

    • 昵称
    • 邮箱
    • 网址