Python3實(shí)現(xiàn)mysql連接和數(shù)據(jù)框的形成,具體代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# -*- coding:utf-8 -*- # __author__ = "LQ" import pymysql import pandas as pd import numpy as np from sklearn import preprocessing #返回?cái)?shù)據(jù)庫連接 def dbcconnect(): conn = pymysql.connect(host = 'ip' , port = 3306 , user = 'username' , passwd = 'password' ,db = 'db' ) return conn #接收sql返回查詢結(jié)果 def selects(sql): conn = dbcconnect() cursor = conn.cursor() cursor.execute(sql) # 獲取剩余結(jié)果所有數(shù)據(jù) results = cursor.fetchall() conn.commit() cursor.close() return results #接收sql返回?cái)?shù)據(jù)框 def selectDf(sql): conn = dbcconnect() cursor = conn.cursor() cursor.execute(sql) # 獲取剩余結(jié)果所有數(shù)據(jù) results = cursor.fetchall() # 獲取列名 cols = [i[ 0 ] for i in cursor.description] # sql內(nèi)表轉(zhuǎn)換pandas的DF df = pd.DataFrame(np.array(results), columns = cols).astype( float ) conn.commit() cursor.close() return df |
總結(jié)
以上所述是小編給大家介紹的Python3實(shí)現(xiàn)mysql連接和數(shù)據(jù)框的形成,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
原文鏈接:https://blog.csdn.net/qq_30868737/article/details/103995174