8.2.3 Operating the MySQL database

  Python can use the MySQLDb module to access the MySQL database. The main methods of this module are as follows:

    (1) commit(): Commit the transaction.

    (2) rollback(): Roll back the transaction.

    (3) callproc(self, procname, args): used to execute the stored procedure, the accepted parameters are the stored procedure name and the parameter list, and the return value is the number of affected rows.

    (4) execute(self, query, ages): Execute a single SQL statement, the receiving side parameters are the SQL statement itself and the parameter list used, and the return value is the number of affected rows.

    (5) executemany(self, query, args): Execute a single SQL statement, but repeatedly execute the parameters in the parameter list, and the return value is the affected function.

    (6) nextset(self): move to the next result set.

    (7) fetchall(self): Receive all the returned result rows.

    (8) fetchmany(self, size=None): Receive the returned result of size bar. If the value of size is greater than the number of returned result rows, cursor.arraysize data will be returned.

    (9) fetchone(self): Returns a result row.

    (10) scroll(self, value, mode='relative'): move the pointer to a row, if mode='relative', it means to move value records from the current row; if mode='absoulte', it means from The first row of the result set moves value records.

1  import MySQLdb
 2  
3  #Query data from MySQL database 
4  
5  try :
 6          conn = MySQLdb.connect(host= ' localhost ' ,user= ' root ' ,passwd= ' root ' ,db= ' test ' ,port=3306 )
 7          cur = conn.cursor()
 8          cur.execute( ' select * from user ' )
 9          cur.close()
 10          conn.close()
 11  exceptMySQLdb.Error as e:
 12      print ( ' MySQL Error %d:%s ' %(e.args[0],e.args[1 ]))
 13  
14  
15  #Insert data into MySQL database 
16  try :
 17      conn = MySQLdb.connect(host= ' localhost ' , user= ' root ' , passwd= ' root ' , db= ' test ' , port=3306 )
 18      cur = conn.cursor()
 19      cur.execute( ' create database if not exists python ')
20     conn.select_db('python')
21     cur.execute('create table test(id int,info varchar(20))')
22     value=[1,'hi rollen']
23     cur.execute('insert into test values(%s,%s)',value)
24     values = []
25     for i in range(20):
26         values.append((i,'hi rollen'+str(i)))
27         
28     cur.executemany('insert into test values(%s,%s)',values)
29     cur.execute('update test set info = "I am rollen" where id = 3')
30     conn.commit()
31     cur.close()
32     conn.close()
33 except MySQLdb.Error as e:
34     print('MySQL Error %d:%s' % (e.args[0], e.args[1]))

 

Guess you like

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