標籤:
test_connection
1 import MySQLdb 2 3 conn = MySQLdb.Connect( 4 host = ‘127.0.0.1‘, 5 port = 3306, 6 user = ‘*****‘, 7 passwd = ‘*****‘, 8 db = ‘czy‘, 9 charset = ‘utf8‘10 )11 12 cursor = conn.cursor()13 14 print conn15 print cursor16 17 cursor.close()18 conn.close()
結果:
<_mysql.connection open to ‘127.0.0.1‘ at 21f0980><MySQLdb.cursors.Cursor object at 0x0228BA30>
test_coursor:
1 import MySQLdb 2 3 conn = MySQLdb.Connect( 4 host = ‘127.0.0.1‘, 5 port = 3306, 6 user = ‘****‘, 7 passwd = ‘****‘, 8 db = ‘czy‘, 9 charset = ‘utf8‘10 )11 12 cursor = conn.cursor()13 14 sql = "select * from user"15 cursor.execute(sql)16 17 print cursor.rowcount18 19 rs = cursor.fetchone()20 print rs21 22 rs = cursor.fetchmany(3)23 print rs24 25 rs = cursor.fetchall()26 print rs27 28 cursor.close()29 conn.close()
結果:
1 92 (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 import MySQLdb 2 3 conn = MySQLdb.Connect( 4 host = ‘127.0.0.1‘, 5 port = 3306, 6 user = ‘**‘, 7 passwd = ‘**‘, 8 db = ‘czy‘, 9 charset = ‘utf8‘10 )11 12 cursor = conn.cursor()13 14 sql = "select * from user"15 cursor.execute(sql)16 17 rs = cursor.fetchall()18 19 for row in rs:20 print "userid = %s,username = %s" % row21 22 cursor.close()23 conn.close()
結果:
userid = 1,username = name1userid = 2,username = name2userid = 3,username = name3userid = 4,username = name4userid = 5,username = name5userid = 6,username = name6userid = 7,username = name7userid = 8,username = name8userid = 9,username = name9
test_iud:
1 import MySQLdb 2 3 conn = MySQLdb.Connect( 4 host = ‘127.0.0.1‘, 5 port = 3306, 6 user = ‘‘, 7 passwd = ‘‘, 8 db = ‘czy‘, 9 charset = ‘utf8‘10 )11 12 cursor = conn.cursor()13 14 sql_insert = "insert into user(userid,username) values(10,‘name10‘)"15 sql_update = "update user set username=‘name91‘ where userid=9"16 sql_delete = "delete from user where userd<3"17 18 try:19 cursor.execute(sql_insert)20 print cursor.rowcount 21 22 cursor.execute(sql_update)23 print cursor.rowcount 24 25 cursor.execute(sql_delete)26 print cursor.rowcount 27 28 conn.commit()29 except Exception, e:30 print e31 conn.rollback()32 33 34 35 cursor.close()36 conn.close()
結果(沒有影響資料庫,因為第三條語句失敗了):
11(1054, "Unknown column ‘userd‘ in ‘where clause‘")
慕課 python 操作資料庫