python mysql 学习笔记
2016-09-22 17:42
337 查看
#!/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()
相关文章推荐
- python 与 mysql 学习笔记一
- python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法
- Python学习笔记10-Python MysqlHelper ,MySql 辅助类
- python+Django+pycharm+mysql 环境搭建及第一个项目学习笔记
- python 学习笔记-操作mysql
- Python 学习笔记 - 操作MySQL
- python学习笔记-安装mysql-python:EnvironmentError: mysql_config not found
- python-MySQL学习笔记-第五章-利用Connector/Python来修改数据库
- Python学习笔记——Python中使用Mysql
- python2学习笔记之mysql连接,中文乱码的解决和文件api的使用
- python学习笔记-安装mysql-python:EnvironmentError: mysql_config not found
- Python学习笔记10-Python MysqlHelper ,MySql 辅助类
- Python的学习笔记DAY12---python和Mysql之二
- Python - mysql中导入CSV数据 【学习笔记】
- python-MySQL学习笔记-第一章链接到并创建数据库
- python-MySQL学习笔记-第三章-利用Connector/Python来插入数据
- python-MySQL学习笔记-第六章-Connector/Python连接池(Connection Pooling)
- Python学习总结笔记(9)-- MySQL数据库操作之mysql-connector
- linux+python+djiango+mysql编译安装学习笔记