這里介紹兩種連接方法,一種是使用安裝的第三方庫pymysql【針對python3】進(jìn)行連接,另外一種是采用pandas里的模塊進(jìn)行連接,個人推薦后者。
?
一、使用pymsql 庫進(jìn)行連接
這里使用的【數(shù)據(jù)庫名:test_my? ? 表名:department? ?字段名為:Id 和 Name】
1. 簡單連接的小例子
? ? (1). 查找記錄。
from pymysql import *
try:
# 連接包括六部分組成:主機(jī)、端口、數(shù)據(jù)庫名、用戶名、密碼、編碼
## 主機(jī):本地使用"localhost"或127.0.0.1【其他使用ip地址即可】、 端口默認(rèn)3306、 "test_my" 是數(shù)據(jù)庫名
## 用戶名默認(rèn)root、密碼為空【若有密碼填入密碼】、編碼'utf8'
conn = connect(host='localhost',port=3306,database='test_my',user='root',passwd='',charset='utf8') # 1.創(chuàng)建連接
cur = conn.cursor() # 2.創(chuàng)建游標(biāo)
id = input('請輸入要查找的Id:')
sql = 'select * from department where Id=%s' # 3.編寫SQL語句 %s 為占位符
cur.execute(sql,[id]) # 4. 游標(biāo)執(zhí)行sql語句【傳入?yún)?shù)】
print(cur.fetchall()) # 5. 游標(biāo)查找全部 【把fetchall 改為fetchone為查找一條數(shù)據(jù)】
cur.close() ## 6. 關(guān)閉游標(biāo)
conn.close() ## 7. 關(guān)閉連接
except Exception:
print("錯誤")
查找前的數(shù)據(jù)庫內(nèi)容:
程序運(yùn)行結(jié)果
(2)增、刪、改數(shù)據(jù)庫(cud)
? ? 這里與上述查詢有些差異、增刪改數(shù)據(jù)庫需要使用事物、需要對執(zhí)行后的語句,再進(jìn)行提交,即commit()操作。而查詢使用的是游標(biāo)再feachone()或feachall()。增刪改則為在游標(biāo)執(zhí)行完sql語句后,再進(jìn)行連接.commit()操作。例子如下
from pymysql import *
try:
# 連接包括六部分組成:主機(jī)、端口、數(shù)據(jù)庫名、用戶名、密碼、編碼
## 主機(jī):本地使用"localhost"或127.0.0.1【其他使用ip地址即可】、 端口默認(rèn)3306、 "test_my" 是數(shù)據(jù)庫名
## 用戶名默認(rèn)root、密碼為空【若有密碼填入密碼】、編碼'utf8'
conn = connect(host='localhost',port=3306,database='test_my',user='root',passwd='',charset='utf8') # 1.創(chuàng)建連接
cur = conn.cursor() # 2.創(chuàng)建游標(biāo)
############ 不同于上述 查詢的 部分
name = input('請輸入要插入的姓名:')
sql_s = 'insert into department(Name) values(%s)' # 3.編寫sql 插入語句 Name是字段
cur.execute(sql_s,[name]) # 4. 游標(biāo)執(zhí)行sql語句【傳入?yún)?shù)】
conn.commit() # 5. 連接提交事務(wù)
###########
cur.close() ## 6. 關(guān)閉游標(biāo)
conn.close() ## 7. 關(guān)閉連接
print('ok')
except Exception:
print("錯誤")
2. 編寫腳本【便于重復(fù)使用】
(1) mysql_help.py 【已經(jīng)編寫好的模塊、用于增刪改查】 ,具體代碼如下
from pymysql import *
class MysqlHelper(object):
def __init__(self,host,port,database,user,passwd,charset='utf8'):
self.host = host
self.port = port
self.database = database
self.user = user
self.passwd = passwd
self.charset = charset
def open(self):
"""創(chuàng)建"""
self.conn = connect(host=self.host,port=self.port,\
database=self.database,passwd=self.passwd,charset=self.charset)
self.cur = self.conn.cursor()
def close(self):
"""關(guān)閉"""
self.cur.close()
self.conn.close()
def cud(self,sql,params):
"""增刪改"""
self.open()
self.cur.execute(sql,params)
self.conn.commit()
self.close()
print('修改成功')
def r_s(self,sql,params):
"""查找"""
try:
self.open()
self.cur.execute(sql,params)
s_result = self.cur.fetchone()
self.close()
return s_result
except Exception:
print("錯誤")
(2)調(diào)用上述腳本,從而更加便捷的進(jìn)行增刪改查【更多精力放在SQL語句編寫上】
? ?再編寫一個python文件叫 sql_execute.py ,讓這個文件與上述的基本腳本文件 mysql_help.py 放在同一目錄下。
?
執(zhí)行前的數(shù)據(jù)庫內(nèi)容如圖:
? 1)當(dāng)需要執(zhí)行 查詢操作 時,sql_execute.py文件調(diào)用的程序如下所示:
import mysql_help
## 1.查找
id_no = input('請輸入要查詢的Id號:')
sql_s = 'select * from department where Id = %s'
mysqlhelper = mysql_help.MysqlHelper('localhost',3306,'test_my','root','')
result = mysqlhelper.r_s(sql_s,[id_no])
print(result)
結(jié)果如下所示:
? ? ? ? 2) 當(dāng)執(zhí)行修改操作【這里僅舉例了更新操作、其余類似】時,程序如下所示:
import mysql_help
#### 2. 更新操作
id_no = input('請輸入要變更的Id號:')
name = input('請輸入要變更后的姓名:')
sql_u = 'update department set Name = %s where Id = %s'
mysqlhelper = mysql_help.MysqlHelper('localhost',3306,'test_my','root','')
mysqlhelper.cud(sql_u,[name,id_no])
程序執(zhí)行結(jié)果
執(zhí)行前的數(shù)據(jù)庫內(nèi)容為:
所以以后直接可以使用腳本 mysql_help.py ?作為自己的基礎(chǔ)腳本。直接調(diào)用即可,把精力放在SQL語句上。
?
二、使用pandas庫進(jìn)行數(shù)據(jù)庫連接查詢
使用pandas.read_sql()
注:這里只針對查詢操作【需要安裝的第三方庫、mysql.connector、pandas、sqlalchemy】
查詢使用如下:
import pandas as pd
from sqlalchemy import create_engine
def readsql(sql_lag,db='test_my'):
engine = create_engine('mysql+mysqlconnector://root:""@localhost:3306/{0}?charset-utf8'.format(db))
df = pd.read_sql(sql_lag,engine)
return df
sql_s = """
select * from department
"""
df1 = readsql(sql_s)
print(type(df1))
print(df1)
其中輸出結(jié)果為DataFrame格式。即數(shù)據(jù)框格式。便于數(shù)據(jù)處理分析。
輸出結(jié)果如下圖所示:
?
?
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
