本次代碼實(shí)現(xiàn)連接遠(yuǎn)程服務(wù)器
由于MySQL服務(wù)器以獨(dú)立的進(jìn)程運(yùn)行辉饱,并通過(guò)網(wǎng)絡(luò)對(duì)外服務(wù),所以拣展,需要支持Python的MySQL驅(qū)動(dòng)來(lái)連接到MySQL服務(wù)器彭沼。
目前,MySQL驅(qū)動(dòng)有幾種:
mysql-connector-python:是MySQL官方的純Python驅(qū)動(dòng)备埃;
MySQL-python:是封裝了MySQL C驅(qū)動(dòng)的Python驅(qū)動(dòng)姓惑。
安裝MySQL驅(qū)動(dòng):
pip install mysql-connector-python
測(cè)試是否安裝成功,測(cè)試python下是否可成功導(dǎo)入mysql.connector即可(import mysql.connector)
pip install MySQL-python (不支持python3)
測(cè)試是否安裝成功按脚,測(cè)試python下是否可成功導(dǎo)入MySQLdb即可(import MySQLdb)
pip install mysqlclient (mysqlclient 完全兼容MySQLdb于毙,同時(shí)支持python3)
測(cè)試是否安裝成功,測(cè)試python下是否可成功導(dǎo)入MySQLdb即可(import MySQLdb)
pip install PyMySQL
測(cè)試是否安裝成功辅搬,測(cè)試python下是否可成功導(dǎo)入pymysql即可(import pymysql)
方式一:pandas中使用SQLAlchemy
SQLAlchemy是Python編程語(yǔ)言下的一款開(kāi)源軟件唯沮。提供了SQL工具包及對(duì)象關(guān)系映射(ORM)工具脖旱,使用MIT許可證發(fā)行SQLAlchemy模塊提供了create_engine()函數(shù)用來(lái)初始化數(shù)據(jù)庫(kù)連接,SQLAlchemy用一個(gè)字符串表示連接信息:'數(shù)據(jù)庫(kù)類(lèi)型+數(shù)據(jù)庫(kù)驅(qū)動(dòng)名稱://用戶名:口令@機(jī)器地址:端口號(hào)/數(shù)據(jù)庫(kù)名'
我們需要以下三個(gè)庫(kù)來(lái)實(shí)現(xiàn)Pandas讀寫(xiě)MySQL數(shù)據(jù)庫(kù):
pandas
sqlalchemy
pymysql
image.png
import pandas as pd
import pymysql
from sqlalchemy import create_engine
# 初始化數(shù)據(jù)庫(kù)連接介蛉,使用pymysql模塊
# MySQL的用戶:root, 密碼:147369, 端口:3306,數(shù)據(jù)庫(kù):test
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test'charset=utf8)
# 查詢語(yǔ)句萌庆,查詢employee表中的所有數(shù)據(jù)
sql = ''' select * from employee; '''
# read_sql_query的兩個(gè)參數(shù): sql語(yǔ)句, 數(shù)據(jù)庫(kù)連接
df = pd.read_sql_query(sql, engine)
# 輸出employee表的查詢結(jié)果
df
# 新建pandas中的DataFrame, 只有id,num兩列
df = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['zhangsan', 'lisi', 'wangwu', 'zhuliu']})
# 將新建的DataFrame儲(chǔ)存為MySQL中的數(shù)據(jù)表币旧,儲(chǔ)存index列
df.to_sql('mydf', engine, index=True)
print('Read from and write to Mysql table successfully!')
示例的Python代碼如下:
1 # -*- coding: utf-8 -*-
2
3 # 導(dǎo)入必要模塊
4 import pandas as pd 5 from sqlalchemy import create_engine 6
7 # 初始化數(shù)據(jù)庫(kù)連接践险,使用pymysql模塊
8 db_info = {'user': 'root',
9 'password': '123456', 10 'host': 'localhost', 11 'port': 3306, 12 'database': 'test'
13 } 14
15 engine = create_engine('mysql+pymysql://%(user)s:%(password)s@%(host)s:%(port)d/%(database)s?charset=utf8' % db_info, encoding='utf-8') 16 # 直接使用下一種形式也可以
17 # engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
18
19 # 讀取本地CSV文件
20 df = pd.read_csv("C:/Users/fuqia/Desktop/example.csv", sep=',') 21 print(df) 22 # 將新建的DataFrame儲(chǔ)存為MySQL中的數(shù)據(jù)表,不儲(chǔ)存index列(index=False)
23 # if_exists:
24 # 1.fail:如果表存在吹菱,啥也不做
25 # 2.replace:如果表存在巍虫,刪了表,再建立一個(gè)新表鳍刷,把數(shù)據(jù)插入
26 # 3.append:如果表存在占遥,把數(shù)據(jù)插入,如果表不存在創(chuàng)建一個(gè)表G憬恕筷频!
27 pd.io.sql.to_sql(df, 'example', con=engine, index=False, if_exists='replace') 28 # df.to_sql('example', con=engine, if_exists='replace')這種形式也可以
29 print("Write to MySQL successfully!")</pre>
方式二:使用pymysql
image.png
# 方式二:
import pymysql
pip install PyMySQL
# 為了兼容mysqldb,只需要加入
pymysql.install_as_MySQLdb()
# 打開(kāi)數(shù)據(jù)庫(kù)連接
conn = pymysql.connect(host='*.*.*.*',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
# 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
cursor = conn.cursor()
# 使用 execute() 方法執(zhí)行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
# 使用 fetchone() 方法獲取單條數(shù)據(jù);使用 fetchall() 方法獲取所有數(shù)據(jù)
data = cursor.fetchall()
for item in data:
print(item[0])
# 關(guān)閉數(shù)據(jù)庫(kù)連接
cursor.close()
或者
import pymysql
param = {
'host':'localhost',
'port':3306,
'db':'tp',
'user':'root',
'password':'dao0206',
'charset':'utf8',
}
conn = pymysql.connect(**param) #連接對(duì)象
cur = conn.cursor() #游標(biāo)對(duì)象前痘,采用默認(rèn)的數(shù)據(jù)格式
cur.execute("SELECT * FROM test") #執(zhí)行sql語(yǔ)句凛捏,返回受影響的行數(shù)
cur.fetchall() #獲取查詢結(jié)果
# %s:占位符
# params:增加內(nèi)容的列表或元組,多條語(yǔ)句可以使用嵌套
sql = "insert into test values(%s,%s)"
params = (1221,"小強(qiáng)")
cur.execute(sql, params) #sql語(yǔ)句參數(shù)化,防止攻擊芹缔!
# pymysql連接數(shù)據(jù)庫(kù)默認(rèn)開(kāi)啟事物坯癣,提交之前的操作,使生效最欠!
conn.commit()
# 要及時(shí)關(guān)閉連接示罗!
cur.close() #關(guān)閉游標(biāo)
conn.close() #關(guān)閉連接
注意:
雖然可以使用cur.execute執(zhí)行create table等語(yǔ)句
但建議在開(kāi)發(fā)之初,就創(chuàng)建好數(shù)據(jù)庫(kù)表結(jié)構(gòu)芝硬,然后再將數(shù)據(jù)追加到表中
方式三:使用MySQLdb
# 方式三:
import MySQLdb
# 打開(kāi)數(shù)據(jù)庫(kù)連接
conn = MySQLdb.connect(host='*.*.*.*',
port=3306,
user='*',
passwd='*',
charset = 'utf8'
)
# 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
cursor = conn.cursor()
# 使用 execute() 方法執(zhí)行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
# 使用 fetchone() 方法獲取單條數(shù)據(jù);使用 fetchall() 方法獲取所有數(shù)據(jù)
data = cursor.fetchall()
for item in data:
print(item)
# 關(guān)閉數(shù)據(jù)庫(kù)連接
cursor.close()
方式四:使用mysql.connector
# 方式四:
import mysql.connector
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = mysql.connector.connect(host='*.*.*.*',
port=3306,
user='*', # 數(shù)據(jù)庫(kù)IP蚜点、用戶名和密碼
passwd='*',
charset = 'utf8')
# 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
cursor = db.cursor()
# 使用 execute() 方法執(zhí)行 SQL 查詢
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
# 使用 fetchone() 方法獲取單條數(shù)據(jù);使用 fetchall() 方法獲取所有數(shù)據(jù)
data = cursor.fetchall()
for item in data:
print(item[0])
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
image.png
參考文章:
https://www.cnblogs.com/kristin/p/10718048.html
http://www.reibang.com/p/32e63b8aa1c2
https://www.cnblogs.com/fuqia/p/8996033.html