Python3实现mysql连接和数据框的形成,具体代码如下所示:
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 #返回数据库连接 def dbcconnect(): conn = pymysql.connect(host = 'ip' , port = 3306 , user = 'username' , passwd = 'password' ,db = 'db' ) return conn #接收sql返回查询结果 def selects(sql): conn = dbcconnect() cursor = conn.cursor() cursor.execute(sql) # 获取剩余结果所有数据 results = cursor.fetchall() conn.commit() cursor.close() return results #接收sql返回数据框 def selectDf(sql): conn = dbcconnect() cursor = conn.cursor() cursor.execute(sql) # 获取剩余结果所有数据 results = cursor.fetchall() # 获取列名 cols = [i[ 0 ] for i in cursor.description] # sql内表转换pandas的DF df = pd.DataFrame(np.array(results), columns = cols).astype( float ) conn.commit() cursor.close() return df |
总结
以上所述是小编给大家介绍的Python3实现mysql连接和数据框的形成,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
原文链接:https://blog.csdn.net/qq_30868737/article/details/103995174