python mysql 学习笔记

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接

# connect()的参数列表如下:

# host,连接的数据库服务器主机名,默认为本地主机(localhost)。
#
# user,连接数据库的用户名,默认为当前用户。
#
# passwd,连接密码,没有默认值。
#
# db,连接的数据库名,没有默认值。


db = MySQLdb.connect('localhost', 'root', 'lsr123', 'studentInfo')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

#utf8 编码
cursor.execute('SET NAMES UTF8')

# 插入学生 李雷
cursor.execute("insert into oneClass(name,age) values('王大力',11)")


 
 
#如果 crazy 名字存在就不插入
cursor.execute( "insert into oneClass(name, age) select 'crazy', 11 from DUAL where not exists(select name from oneClass where name = 'crazy')" )
 # 数据库的更新 cursor.execute("update oneClass set age = 6 where name = '胜任'") # 删除操作 try: cursor.execute("delete from oneClass where id between 7 and 9") except: # 发生错误时回滚 db.rollback() #查询 id = 1 的数据 try: cursor.execute("select *from oneClass where id = 10") results = cursor.fetchall() for row in results: name = row[1] age = row[2] print name print age except: print "not found" # 向数据库提交 db.commit() # 关闭数据库连接 db.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值