python 连接mysql数据库 进行增删改查操作

1、在进行连接之前我们要确定我们已经安装了python和mysql(开玩笑,没有这个你怎么连接那)至于安装的过程在此略过,

2、因为要进行连接mysqldb 所有我们要导入MySQLdb的模块,当然这个模块在默认的python中是没有的,https://pypi.python.org/pypi/MySQL-python/1.2.5我们可以在这里进行下载,安装;

3、代码

import MySQLdb   (导入MySQLdb 模块)
conn = MySQLdb.connect( host='localhost',user='root',passwd='')
conn.select_db('test')(选择数据库)

以上是连接数据库的代码 切记注意MySQLdb 的大小写的区分 ,否则会报错:ImportError: No module named MYSQLdb

增加;

sql='''insert into user (name) values(1)'''
try:
    cursor.execute(sql)
    conn.commit()
except :
conn.rollback()
conn.close();

删除:

sql='''delete from user where id =1'''
try:
cursor.execute(sql)
conn.commit()
except Exception, e:
conn.rollback();
print cursor.execute(sql)
else:
print cursor.execute(sql)
finally:
conn.close()

修改:

sql = "update user set name='zhy' where id=2"
cursor.execute(sql)
conn.commit()

查询:

result=cursor.execute('''select * from user''')
# print result
row = cursor.fetchall()
for r in row:
  print r[1](这里是每个字段的号)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值