#!/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()
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐