python mysqldb 模塊學習

 
1、安裝(環境win7 、python2.7)
Python2.x 版本,使用MySQL-python:
安裝包:MySQL-python-1.2.5.win32-py2.7.exe(雙擊安裝)

下載地址:https://pypi.python.org/pypi/MySQL-python


2、代碼
#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()
相關文章
相關標籤/搜索