python3我们用pymysql和mysql.connector连接和操作mysql数据库
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。
python连接数据库的几种方式
本次代码实现连接远程服务器
由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。
目前,MySQL驱动有几种:
mysql-connector-python:是MySQL官方的纯Python驱动;
MySQL-python:是封装了MySQL C驱动的Python驱动。
安装MySQL驱动:
pip install mysql-connector-python
测试是否安装成功,测试python下是否可成功导入mysql.connector即可(import mysql.connector)
pip install MySQL-python (不支持python3)
测试是否安装成功,测试python下是否可成功导入MySQLdb即可(import MySQLdb)
pip install mysqlclient (mysqlclient 完全兼容MySQLdb,同时支持python3)
测试是否安装成功,测试python下是否可成功导入MySQLdb即可(import MySQLdb)
pip install PyMySQL
测试是否安装成功,测试python下是否可成功导入pymysql即可(import pymysql)
python连接MySQL数据库的多种方式(方式一)
# 方式一:
import mysql.connector
# 打开数据库连接
db = mysql.connector.connect(host='*.*.*.*',
port=3306,
user='*', # 数据库IP、用户名和密码
passwd='*',
charset = 'utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
# 使用 fetchone() 方法获取单条数据;使用 fetchall() 方法获取所有数据
data = cursor.fetchall()
for item in data:
print(item[0])
# 关闭数据库连接
db.close()
python连接MySQL数据库的多种方式(方式二)
# 方式二:
import MySQLdb
# 打开数据库连接
conn = MySQLdb.connect(host='*.*.*.*',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
# 使用 fetchone() 方法获取单条数据;使用 fetchall() 方法获取所有数据
data = cursor.fetchall()
for item in data:
print(item)
# 关闭数据库连接
cursor.close()
python连接MySQL数据库的多种方式(方式三)
# 方式三:
import pymysql
# 打开数据库连接
conn = pymysql.connect(host='*.*.*.*',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
# 使用 fetchone() 方法获取单条数据;使用 fetchall() 方法获取所有数据
data = cursor.fetchall()
for item in data:
print(item[0])
# 关闭数据库连接
cursor.close()
python对MySQL增删改查
一、基本操作
(1) 查询
import pymysql
conn = pymysql.connect(host='127.0.0.1&#