Python 之数据库操作

快乐小王子 / 2024-09-04 / 原文

Python 之数据库操作

目录
  • Python 之数据库操作
    • Pymysql教程
      • 数据库连接

Pymysql教程

介绍:

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库

安装

pip install PyMySQL

数据库连接

#!/usr/bin/python3
 
import pymysql
 
# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='testuser',
                     password='test123',
                     database='TESTDB')
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

参考教程:https://www.runoob.com/python3/python3-mysql.html