第一种:使用pymysql连接并操作MySQL 数据库
`#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print "Database version : %s " % data
# 关闭数据库连接
db.close()`
第二种:使用Pandas库实现MySQL数据库的读写
Pandas读写MySQL数据库
我们需要以下三个库来实现Pandas读写MySQL数据库:
pandas
sqlalchemy
pymysql
# -*- coding: utf-8 -*-
# 导入必要模块
import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:147369, 端口:3306,数据库:mydb
engine = create_engine('mysql+pymysql://root:147369@localhost:3306/mydb')
# 查询语句,选出employee表中的所有数据
sql