【1-3】pythondb增删改查

来源:互联网 发布:流畅的python 编辑:程序博客网 时间:2024/05/29 02:50

效果图

<module 'MySQLdb' from 'C:\Python27\lib\site-packages\MySQLdb\__init__.pyc'>
<_mysql.connection open to 'localhost' at 260daa8>
<MySQLdb.cursors.Cursor object at 0x0000000002A8CC50>
userid=1, username=a
userid=2, username=b
userid=3, username=c
userid=4, username=d
userid=5, username=e
userid=6, username=f
userid=7, username=h
userid=9, username=i
userid=10, username=name10
userid=11, username=name11
1受影响的行数
1受影响的行数
3受影响的行数

增删改语句

# -*- coding:utf-8 -*- 
import MySQLdb
print MySQLdb


conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='t1',port=3306) 
cursor=conn.cursor() 
print conn
print cursor


sql = "select * from user"
cursor.execute(sql)


rs = cursor.fetchall()
for row in rs:
    print "userid=%s, username=%s" % row


sql_insert = "insert into user(userid,username) values(12,'name12')"
sql_update = "update user set username='name9' where userid=9"
sql_delete = "delete from user where userid<4"


cursor.execute(sql_insert)
print cursor.rowcount
cursor.execute(sql_update)
print cursor.rowcount
cursor.execute(sql_delete)
print cursor.rowcount


conn.commit()


rs = cursor.fetchall()
for row in rs:
    print "userid=%s, username=%s" % row


cursor.close() 
conn.close() 

0 0
原创粉丝点击