To operate the mysql database in python, you need to install the pymysql module first. You can read how to install it in the previous blog. The easiest one is pip install pymysql
1. Import the pymysql module import pymysql
2. To connect to the database, you need ip, account, password, port number, database and other information
3. Create a cursor
4. Execute the sql statement
5. Get results
6. Close the cursor
7. Close the connection
import pymysql coon = pymysql.connect(host='192.168.21.129',user='root',passwd='123456',port=3306,db='test',charset='utf8') cur = coon.cursor() sql = 'select * from user' cur.execute(sql) res = cur.fetchall() print(res) cur.close() coon.close()
import pymysql coon = pymysql.connect(host='192.168.21.129',user='root',passwd='123456',port=3306,db='test',charset='utf8') cur = coon.cursor() #Create a cursor cur.execute('insert into user(username,passwd) VALUE ("2222","4444");') #执行sql coon.commit() #delete update insert must have coomit cur.close() #Close the cursor coon.close() #Close the connection
When executing the select statement and the delete update insert statement, we can define a function and use the condition to judge the sql statement in the function
def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'): import pymysql coon = pymysql.connect(user=user, host=host, port = port, passwd=passwd, db=db, charset=charset ) cur = coon.cursor() #Create a cursor cur.execute(sql)#Execute sql if sql.strip()[: 6 ].upper()== ' SELECT ' : #The sql statement slice takes the first 6 digits, then converts them to uppercase letters, and then compares them res = cur.fetchall() else: coon.commit() res = 'ok' cur.close() coon.close() return res