Ways to read sql from python:
1. Use python's built-in open function to read in the sql file;
2、Use the connect function in the third-party library pymysql to connect to the mysql server;
3, the use of third-party library pandas in the read_sql method to read the incoming sql file can be.
python reads the sql file directly for the purpose of using the read_sql executable.
# sql folder path sql_path = 'sql folder path' + '\\' # sql filename, .sql suffixed sql_file = 'sql file name.sql' # Read sql file text contents sql = open(sql_path + sql_file, 'r', encoding = 'utf8') sqltxt = () # At this point, sqltxt is a list # Close the file after reading () # list to str sql = "".join(sqltxt) import pandas as pd import pymysql con = (host = "The Machine.", user = "Username", password = 'Password', db = "Database name", charset='utf8') # charset is used to fix the problem of question marks in Chinese output. df = pd.read_sql(sql, con) ()
Content Extension:
python3 pandas reading MySQL data
import pandas as pd import pymysql con = (host = "localhost", user = "root", password = '12', db = "test", charset='utf8') #charset is used to fix the problem of question marks in Chinese output. sql = "select * from score;" df = pd.read_sql(sql, con) ()
Above is the details of the example method to read sql from python, for more information on how to read sql from python please follow my other related articles!