python操作mysql
方法一:使用mysql.connector库
先安装python库 pip install mysql-connector,然后使用如下代码
import mysql.connector
# 打开数据库连接(请根据自己的用户名、密码及数据库名称进行修改)
cnn = mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',port=3306,database='test')
# 使用cursor()方法获取操作游标
cursor = cnn.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 执行sql语句
cnn.close()
方法二:使用pymysql库
先安装python库 pip install PyMySQL,然后使用如下代码
import pymysql
# 打开数据库连接(请根据自己的用户名、密码及数据库名称进行修改)
cnn = pymysql.connect(user='root',passwd='root',host='127.0.0.1',port=3306,database='test')
# 使用cursor()方法获取操作游标
cursor = cnn.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 执行sql语句
cnn.close()
python执行SQL命令
python安装上述方法连接上mysql数据库后,只需要按照需求写好sql语句,然后用 cursor.execute(sql) 执行即可,如
SQL= "create database if not exists db1;"
cursor.execute(SQL)

本文介绍了Python连接和操作MySQL数据库的两种方法,包括使用mysql.connector和pymysql库。通过示例代码展示了如何建立连接、执行SQL(如查询数据库版本)以及关闭连接。这些方法适用于Python开发人员在日常工作中进行数据库交互。
1528

被折叠的 条评论
为什么被折叠?



