Python使用MySQLdb操作MySQL

本文提供了一个使用Python连接MySQL数据库并进行增删改查(CRUD)操作的完整示例,包括插入单条和多条记录、删除记录、更新记录及查询所有记录。
import MySQLdb,sys

try:
    
    conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='123',db='db1')

except Exception,e:
    print e
    sys.exit(0)
    
cursor=conn.cursor()
try:#Add
    cursor.execute("insert into table1(name,address,year) values('Jack2','ddd','2011-5-8')")    
    cursor.execute("insert into table1(id,name,address,year) values(%d,'%s','%s','%s')"%(99,"Jack","USA","1990-9-9"))    #注意,这里是'%s'是带单引号的!!!
except Exception,e:
    print e
try:#Delete
    cursor.execute("delete from table1 where name='Jack2'") 
except Exception,e:
    print e  
try:#Change
    cursor.execute("update table1 set name='YY' where address='XiAn'")
except Exception, e:
    print e

try:#AddMulti
    sql="insert into table1(name,address,year) values(%s,%s,%s)"     #而这里是%s,不带单引号的。数字怎么处理。我写个%d,在下面分别写上数字编号6,,6,666却显示错误。
    var=(("Bu1","Japan","2011-1-1"),("Bu2","Japan","2011-1-2"),("Bu3","Japan","2011-1-3"))
    cursor.executemany(sql,var)
except Exception,e:
    print e    
sql="select * from table1"
try:#Search
    cursor.execute(sql)
except Exception,e:
    print e
rows=cursor.fetchall()
if rows:
    for item in rows:
        print item[0],item[1],item[2],item[3]

cursor.close()
conn.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值