使用Python操控MySQL数据库
2015-09-05 01:26
666 查看
使用Python操控MySQL数据库
1.MySQLdb的简单示例
import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='xxx',db='xxx',port=3306) cur=conn.cursor() cur.execute('select * from user') cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
2.MySQL相关操作
其实Python下对MySQL进行操作和直接使用MySQL Shell的方法差不多,只是需要多写几条模板代码而已。另外,记得最后commit()。import MySQLdb try: conn = MySQLdb.connect(host='localhost',user='root',passwd='xxx',port=3306) cur = conn.cursor() cur.execute('create database if not exists test_db') conn.select_db('test_db') cur.execute('create table test_tb(id int,name char(20))') #单条INSERT cur.execute('INSERT INTO test_tb VALUES(%s,%s)',[1,'Elfsong']) #批量INSERT values=[] for i in range(20): values.append((i,'i')) cur.executemany('INSERT INTO test_tb VALUES(%s,%s)',values) #修改 cur.execute('UPDATA test_tb SET name = "Sony" WHERE id = 1') conn.commit() cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
3.常用的函数
MySQL连接对象提供了对事务操作的支持,标准的方法:
commit() 提交rollback() 回滚
cursor执行命令的方法:
callproc(self, procname, args) :用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数execute(self, query, args) :执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args) :执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self): 移动到下一个结果集
cursor接收返回值的方法:
fetchall(self): 接收全部的返回结果行.fetchmany(self, size=None): 接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self): 返回一条结果行.
scroll(self, value, mode=’relative’): 移动指针到某一行.如果mode=’relative’,则表示从当前所在行移动value条,如果 mode=’absolute’,则表示从结果集的第一行移动value条.
相关文章推荐
- Python爬虫教程——入门六之Cookie的使用
- Python-selenium基础操作
- [python]学渣的心酸(求职篇)
- Python爬虫教程——入门五之URLError异常处理
- Python爬虫教程——入门四之Urllib库的高级用法
- Python爬虫教程——入门三之Urllib库的基本使用
- Python爬虫教程——入门一之爬虫基础了解
- Python爬虫教程——入门一之综述
- webdriver 验证码问题 selenium_python
- webdriver cookie 处理 selenium_python
- Python 3.3 Tutorial Notes - 8:Standard Libraries - Briefly
- Python 3.3 Tutorial Notes - 7:Class
- Python 3.3 Tutorial Notes - 6:Error and Exception
- Python 3.3 Tutorial Notes - 5:Input and Output
- Python 3.3 Tutorial Notes - 4:Modules
- Python 3.3 Tutorial Notes - 3:Data Structure
- Python 3.3 Tutorial Notes - 2:Control Flow
- Python 3.3 Tutorial Notes - 1:Basic
- Python 3.3 Tutorial - Online Resource
- webdriver控制浏览器滚动条 selenium_python