MySQLdb operation of MySQL database. Let's start with a simple example:
1 ImportMySQLdb2 3 Try:4Conn=mysqldb.connect (host='localhost', user='Root', passwd='Root', db='Test', port=3306)5Cur=conn.cursor ()6Cur.execute ('SELECT * from user')7 cur.close ()8 conn.close ()9 exceptmysqldb.error,e:Ten Print "Mysql Error%d:%s"% (E.args[0], e.args[1])
Insert data, BULK INSERT data, update data!
1 ImportMySQLdb2 3 Try:4Conn=mysqldb.connect (host='localhost', user='Root', passwd='Root', port=3306)5Cur=conn.cursor ()6 7Cur.execute ('CREATE database if not exists Python')8conn.select_db ('python')9Cur.execute ('CREATE TABLE Test (ID int,info varchar )')Ten OneValue=[1,'Hi Rollen'] ACur.execute ('INSERT into test values (%s,%s)', value) - -values=[] the forIinchRange (20): -Values.append ((I,'Hi Rollen'+str (i))) - -Cur.executemany ('INSERT into test values (%s,%s)', values) + -Cur.execute ('Update test set info= "I am Rollen" where id=3') + A Conn.commit () at cur.close () - conn.close () - - exceptmysqldb.error,e: - Print "Mysql Error%d:%s"% (E.args[0], e.args[1])
Please note that you must have conn.commit () to commit the transaction , or you cannot actually insert the data.
1 ImportMySQLdb2 3 Try:4Conn=mysqldb.connect (host='localhost', user='Root', passwd='Root', port=3306,charset= ' UTF8 ')5Cur=conn.cursor ()6 7conn.select_db ('python')8 9Count=cur.execute ('SELECT * FROM Test')Ten Print 'There has%s rows record'%Count One Aresult=Cur.fetchone () - Printresult - Print 'ID:%s Info%s'%result the -Results=cur.fetchmany (5) - forRinchResults: - PrintR + - Print '=='*10 +Cur.scroll (0,mode='Absolute') A atresults=Cur.fetchall () - forRinchResults: - PrintR[1] - - - Conn.commit () in cur.close () - conn.close () to + exceptmysqldb.error,e: - Print "Mysql Error%d:%s"% (E.args[0], e.args[1])
Python operation MySQL Database