Example method of reading sql from python

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

Example method of reading sql from python
Python3.7 debugging example method
Python right alignment example method
Python method of parameter passing
Summary of logarithm method in Python
Python calculation of information entropy example
Example operation of python access Alipay
End the method of running python
Method of installing django module in python
Example of python calculating derivative and plotting
The specific method of python instantiation object
Python example method to open music files
The specific method of python import library
Method analysis of Python calling C language program
Detailed explanation of the principle of Python super() method
7 features of Python3.9
Python object-oriented example
Python implementation of AI automatic matting example analysis
Python implementation of hand drawing effect example sharing
Example of feature extraction operation implemented in Python
Example of how to automatically download pictures in python
Python magic method topic
Python object-oriented magic method
Python function-dictionary get() method
Basics of Python syntax
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
Python error handling method
Python interpolate interpolation example
09. Common modules of Python3