This example describes how Python accesses the MySQL database using MYSQLDB. Share to everyone for your reference. Specific as follows:
#!/usr/bin/pythonimport mysqldbdef Doinsert (cursor,db): #insert # Prepare SQL query to insert a record into the database. sql = "UPDATE EMPLOYEE SET age = age+1 WHERE SEX = '%c '"% (' M ') try:cursor.execute (SQL) Db.commit () Except:db.rollbac K () def do_query (cursor,db): sql = "SELECT * from EMPLOYEE \ WHERE INCOME > '%d '"% (n) Try: # Execute the SQL command Cursor.execute (SQL) # Fetch all the rows in a list of lists. Results = Cursor.fetchall () print ' resuts ', cursor.rowcount for row in results:fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # now print fetched result print "Fname=%s,lname=%s,age=%d,sex=%s,in come=%d "% \ (fname, lname, age, sex, income) except:print" error:unable to FECTH data "Def do_delete (cursor,db ): sql = ' DELETE from EMPLOYEE WHERE > {} '. Format (try:cursor.execute) (SQL) Db.commit () Except:db.rollback () def do_insert (cursor,db,firstname,lastname,age,sex,income): sql = "InseRT into EMPLOYEE (first_name, \ last_name, age, SEX, INCOME) \ VALUES ('%s ', '%s ', '%d ', '%c ', '%d ') "% \ (firstn ame,lastname,age,sex,income) try:cursor.execute (SQL) Db.commit () Except:db.rollback () # Open database connection# Chan GE this to your MySQL account#connect (server,username,password,db_name) db = MySQLdb.connect ("localhost", "Hunter", " Hunter "," Pydb ") # Prepare a Cursor object using the cursor () Methodcursor = Db.cursor () do_query (cursor,db) Doinsert (cursor,db ) Do_query (cursor,db) do_delete (cursor,db) do_query (cursor,db) Do_insert (cursor,db, ' Hunter ', ' Xue ', +, ' M ', ') do_ Insert (cursor,db, ' Mary ', ' Yang ', +, ' f ', 5555) Do_insert (cursor,db, ' Zhang ', ' Xue ', +, ' M ', ") Do_insert (Cursor,db, ' Hunter ', ' Xue ', +, ' M ', 333) do_query (cursor,db) # Disconnect from Serverdb.close ()
Hopefully this article will help you with Python programming.