python--operate database

To operate mysql database in python3, you need to install a third-party module, pymysql, which can be installed using pip install pymysql. In python2, it is the MySQLdb module. There is no MySQLdb module in python3, so pymysql is used.

1. Operating the data
Operating the database is divided into the following steps

1. Connect to the database account password ip port number database
2. Create a cursor
3. Execute sql
4. Get the result
5. Close the cursor
6. Close the link

1 sql_connect = pymysql.connect(
 2      host= ' 118.24.3.40 ' , user= ' jxz ' , passwd= ' 123456 ' ,
 3      port=3306, db= ' jxz ' , charset= ' utf8 ' 
4      # port must write int Type 
5      # charset must write utf8 here 
6  )
 7 cur = sql_connect.cursor() #Create a cursor 
8 cur.execute( ' select * from stu; ' ) #Execute sql 
9res = cur.fetchall() #Get all the returned results 10 11 # cur.execute('insert into stu VALUE (6,"ytt","female");') 12 # delete update insert statement needs to commit 13 # sql_connect.commit() 14 15 print (res)
 16 cur.close() #Close the cursor 17 sql_connect.close() #Close the link
 
 
 
 
 
 

Write a function to operate the database

 1 def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
 2     import  pymysql
 3     coon = pymysql.connect(user=user,
 4                            host=host,
 5                            port=port,
 6                            passwd=passwd,
 7                            db=db,
 8                            charset=charset
 9                            )
10     cur = coon.cursor()#建立游标
11     cur.execute(sql)#执行sql
12     if sql.strip()[:6].upper()=='SELECT':
13         res = cur.fetchall()
14         print(res)
15     else:
16         coon.commit()
17         res = 'ok'
18     cur.close()
19     coon.close()
20     return res

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324971185&siteId=291194637