Test_connection
1 ImportMySQLdb2 3conn =MySQLdb.connect (4Host ='127.0.0.1',5Port = 3306,6user ='*****',7passwd ='*****',8db ='Czy',9CharSet ='UTF8'Ten ) One Acursor =conn.cursor () - - PrintConn the Printcursor - - cursor.close () -Conn.close ()
Results:
' 127.0.0.1 ' at 21f0980><mysqldb.cursors.cursor object at 0x0228ba30>
Test_coursor:
1 ImportMySQLdb2 3conn =MySQLdb.connect (4Host ='127.0.0.1',5Port = 3306,6user ='****',7passwd ='****',8db ='Czy',9CharSet ='UTF8'Ten ) One Acursor =conn.cursor () - -sql ="SELECT * from user" the cursor.execute (SQL) - - PrintCursor.rowcount - +rs =Cursor.fetchone () - PrintRS + Ars = Cursor.fetchmany (3) at PrintRS - -rs =Cursor.fetchall () - PrintRS - - cursor.close () inConn.close ()
Results:
192(1L, U'name1')3(2L, U'name2'), (3L, U'Name3'), (4L, U'Name4'))4(5L, U'Name5'), (6L, U'Name6'), (7L, U'Name7'), (8L, U'Name8'), (9L, U'Name9'))
Test_select:
1 ImportMySQLdb2 3conn =MySQLdb.connect (4Host ='127.0.0.1',5Port = 3306,6user ='**',7passwd ='**',8db ='Czy',9CharSet ='UTF8'Ten ) One Acursor =conn.cursor () - -sql ="SELECT * from user" the cursor.execute (SQL) - -rs =Cursor.fetchall () - + forRowinchRS: - Print "UserID =%s,username =%s"%Row + A cursor.close () atConn.close ()
Results:
UserID = 1,username == 2,username == 3,username == 4,username == 5,username == 6,username == 7,username == 8,username == 9,username = Name9
Test_iud:
1 ImportMySQLdb2 3conn =MySQLdb.connect (4Host ='127.0.0.1',5Port = 3306,6user ='',7passwd ='',8db ='Czy',9CharSet ='UTF8'Ten ) One Acursor =conn.cursor () - -Sql_insert ="INSERT INTO User (Userid,username) VALUES (' Name10 ')" theSql_update ="Update user set username= ' name91 ' where userid=9" -Sql_delete ="Delete from user where userd<3" - - Try: + Cursor.execute (Sql_insert) - PrintCursor.rowcount + A Cursor.execute (sql_update) at PrintCursor.rowcount - - Cursor.execute (sql_delete) - PrintCursor.rowcount - - Conn.commit () in exceptException, E: - Printe to Conn.rollback () + - the * cursor.close () $Conn.close ()
The result (no database is affected because the third statement failed):
One("Unknown column ' UserD ' in ' WHERE clause '")
Mu Class Python operations database