python mysqldb 模块学习
2016-06-21 15:17
369 查看
一、安装(环境win7 、python2.7)
Python2.x 版本,使用MySQL-python:
安装包:MySQL-python-1.2.5.win32-py2.7.exe(双击安装) 下载地址:https://pypi.python.org/pypi/MySQL-python
二、代码 #coding:utf-8 #执行sql:execute、executmany(合理调用executmany,将多个insert放在一起,只执行一次IO,可以有效的提升数据库性能,但executmany不能一次数据量过大) #cur.execute(ssql) #执行sql(一次仅能执行一条) #conn.rollback() #回滚(commit前可做相应回滚,commit后无法再robllback) #conn.commit() #提交到数据库执行(支持事务的存储引擎,需要commit,才真正写入数据库,执行多条sql后再一次调用 commit,可以适当提升性能) #提取数据:fetchone、fetchall、fetchmany # cur.fetchone() #result=cur.fetchall() #结果集 #for row in result: #print result[0][1] #print "Nuber of rows returned: %d" %cur.rowcount #打印总条数,%d:输出整数格式 import MySQLdb import MySQLdb.cursors import time #################连接数据库 #连接数据库 ,MySQLdb.Connect(host ,user , passw , db) class DbOperation(): def __init__(self,host,user,passwd,db): self.db_error_msg=None self.db_result=True self.conn='' self.host=host self.user=user self.passwd=passwd self.db=db try: self.conn=MySQLdb.Connect(self.host,self.user,self.passwd,self.db) #return self.conn except MySQLdb.OperationalError as e: self.db_error_msg=u'连接数据库' + self.conn.user + u'失败!' self.db_result=False #################insert #join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串 def insert(self,table_name,data): for key in data: #for循环遍历字典data的键值key data[key]="'"+str(data[key])+"'" #data[key] :获取key相应元素的值 key=','.join(data.keys()) #字典的元素 value=','.join(data.values()) #字典的元素的值 isql="INSERT INTO " + table_name + " (" + key + ") VALUES (" + value + ")" cur=self.conn.cursor() cur.execute(isql) self.conn.commit() #################执行sql操作 def exesql(self,sql): self.db_result=True cur=self.conn.cursor() try: cur.execute(sql) print "Nuber of rows returned: %d" %cur.rowcount except Exception,msg: self.db_error_msg = u'执行sql语句出错:' + sql self.db_result = False return False #################关闭 def close(self): self.conn.close() if __name__=='__main__': db1=DbOperation('10.118.55.106','test01','123456','test') sql="select * from ts_user" table_name="ts_user" data={'user_id':200000012,'username':100000,'type_code':1,'status':1} #字典 db1.insert(table_name,data) db1.exesql(sql) db1.close()
相关文章推荐
- python logging 转载
- python之map映射
- Python的Django框架中forms表单类的使用方法详解
- 数字的正则表达式,python
- Python爬虫实践(八):正则表达式re模块(2)
- python练习实例之二 利润分红计算
- Python中将函数作为另一个函数的参数传入并调用
- Python 连接Sql Server数据库 MSSql
- Python 连接Sql Server数据库 MSSql
- python远程连接mysql服务器
- 朴素贝叶斯分类器
- python多线程和多进程对比
- numpy.array 操作简单总结
- MNIST 可视化
- Python爬虫实践(七):正则表达式(2) re模块的使用
- 跟Alex学Python之- 这年头不会点算法怎以混江湖? 推荐
- python环境搭建
- python hashlib模块
- Python join函数 基础知识篇
- Python函数返回不定数量的值