Record how python connects to the Mysql database. It will be used frequently in the future. It feels very important.
1. Install the pymysql library
#pip install pymysql
Second, connect to the mysql database
1. Connection steps
2. Practical operation, how to connect the code connection
Connection string:
conn = pymysql.connect(
host='127.0.0.1',user='xxx',passwd='xxxxxxx',
port=3306,db='xxxxx',charset='utf8'
#port must write int type
#charset utf8 must be written here
) #Query
data
#insert data
3. The integration connection process is a function
1. Example
#Encapsulate a function to perform database operations
#Encapsulate a function to perform database operations
def my_db(host,user, passwd, db,sql, port=3306, charset='utf8'):
import pymysql
conn = pymysql.connect(user=user,
host=host,
port=port ,
passwd=passwd,
db=db,
charset=charset
)
cur = conn.cursor() #Create a cursor
cur.execute(sql) #Execute mysql
if sql.strip()[:6].upper() == 'SELECT ':
res = cur.fetchall()
else:
conn.commit()
res = 'ok'
cur.close()
conn.close()
return res