码迷,mamicode.com
首页 > 数据库 > 详细

慕课 python 操作数据库

时间:2016-06-05 09:45:08      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:

 

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 conn
15 print cursor
16 
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.rowcount
18 
19 rs = cursor.fetchone()
20 print rs
21 
22 rs = cursor.fetchmany(3)
23 print rs
24 
25 rs = cursor.fetchall()
26 print rs
27 
28 cursor.close()
29 conn.close()

 

结果:

1 9
2 (1L, uname1)
3 ((2L, uname2), (3L, uname3), (4L, uname4))
4 ((5L, uname5), (6L, uname6), (7L, uname7), (8L, uname8), (9L, uname9))

 

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" % row
21 
22 cursor.close()
23 conn.close()

 

结果:

userid = 1,username = name1
userid = 2,username = name2
userid = 3,username = name3
userid = 4,username = name4
userid = 5,username = name5
userid = 6,username = name6
userid = 7,username = name7
userid = 8,username = name8
userid = 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 e
31     conn.rollback()
32 
33 
34 
35 cursor.close()
36 conn.close()

 

结果(没有影响数据库,因为第三条语句失败了):

1
1
(1054, "Unknown column ‘userd‘ in ‘where clause‘")

 

慕课 python 操作数据库

标签:

原文地址:http://www.cnblogs.com/njczy2010/p/5560086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!