Python 3 realizes MySQL connection and data frame formation (example code)

Time:2020-9-14

Python 3 implements MySQL connection and data frame formation. The specific code is as follows:

# -*- coding:utf-8 -*-
# __author__ = "LQ"
import pymysql
import pandas as pd
import numpy as np
from sklearn import preprocessing
#Back to database connection
def dbcconnect():
  conn = pymysql.connect(host='ip', port=3306, user='username', passwd='password',db='db')
  return conn
#Receive SQL and return query results
def selects(sql):
  conn=dbcconnect()
  cursor = conn.cursor()
  cursor.execute(sql)
  #Get all the data of the remaining results
  results = cursor.fetchall()
  conn.commit()
  cursor.close()
  return results
#Receive SQL and return data frame
def selectDf(sql):
  conn=dbcconnect()
  cursor = conn.cursor()
  cursor.execute(sql)
  #Get all the data of the remaining results
  results = cursor.fetchall()
  #Get column name
  cols = [i[0] for i in cursor.description]
  #DF of pandas in SQL inner table conversion
  df = pd.DataFrame(np.array(results), columns=cols).astype(float)
  conn.commit()
  cursor.close()
  return df

summary

The above is the introduction of Python 3 to you to achieve MySQL connection and data frame formation, I hope to help you, if you have any questions, please leave me a message, the editor will reply you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!