Method to read sql from python:
1、 Use python's built-in open function to read sql files;
2、 Use the connect function in the third-party library pymysql to connect to the mysql server;
3、 Use the read_sql method in the third-party library pandas to read the incoming sql file.
Python reads sql files directly to achieve the purpose of using read_sql to be executable
# sql folder path
sql_path ='sql folder path'+ '\'
# sql file name,.sql suffix
sql_file ='sql file name.sql'
# Read the text content of the sql file
sql =open(sql_path + sql_file,'r', encoding ='utf8')
sqltxt = sql.readlines()
# At this time sqltxt is list type
# Close the file after reading
sql.close()
# list to str
sql ="".join(sqltxt)import pandas as pd
import pymysql
con = pymysql.connect(host ="machine",
user ="username", password ='password',
db ="data storage name", charset='utf8')
# charset is used to correct the problem of Chinese output as a question mark
df = pd.read_sql(sql, con)
con.close()
Content expansion:
python3 pandas read MySQL data
import pandas as pd
import pymysql
con = pymysql.connect(host ="localhost",
user ="root", password ='12',
db ="test", charset='utf8')
# charset is used to correct the problem of Chinese output as a question mark
sql ="select * from score;"
df = pd.read_sql(sql, con)
con.close()
The above is the detailed content of the example method of reading sql from python. For more information on how to read sql from python, please pay attention to other related articles on ZaLou.Cn!
Recommended Posts