#-*-coding:utf8-*-
__author__ = 'yangjing'
import mysqldb
#查詢。
def select(host="",user="root",password="",port=3306,db="",sql=""):
connect = mysqldb.connect(host=host,user=user,passwd=password,port=port,db=db,charset='utf8')
cursor = connect.cursor()
try:
cursor.execute(sql)
result = cursor.fetchall()
except
exception
as ex:
print ex
cursor.close()
connect.close()
return result
#插入。可插入多條記錄,例value=(("abc"),("def"));單條插入時,例value=(("abc"),)
def insert(host="",user="root",password="",port=3306,db="",sql="",value=()):
connect = mysqldb.connect(host=host,user=user,passwd=password,port=port,db=db)
cursor = connect.cursor()
try:
count = cursor.executemany(sql,value)
connect.commit()
except
exception
as ex:
print ex
connect.rollback()
cursor.close()
connect.close()
print u"影響總記錄條數:%d" % count
#更新和刪除。
def updanddel(host="",user="root",password="",port=3306,db="",sql=""):
connect = mysqldb.connect(host=host,user=user,passwd=password,port=port,db=db)
cursor = connect.cursor()
try:
count = cursor.execute(sql)
connect.commit()
except
exception
as ex:
print ex
connect.rollback()
cursor.close()
connect.close()
print u"影響總記錄條數:%d" % count
#多個sql語句作為乙個事務執行。
def multisql(host="",user="root",password="",port=3306,db="",sqllist=):
connect = mysqldb.connect(host=host,user=user,passwd=password,port=port,db=db)
cursor = connect.cursor()
count = 0
try:
forsqlin sqllist:
count = count + cursor.execute(sql)
connect.commit()
except
exception
as ex:
print ex
connect.rollback()
cursor.close()
connect.close()
print u"影響總記錄條數:%d" % count
#執行儲存過程
def procedure(host="",user="root",password="",port=3306,db="",procename="",para=()):
connect = mysqldb.connect(host=host,user=user,passwd=password,port=port,db=db)
cursor = connect.cursor()
try:
cursor.callproc(procename,para)
connect.commit()
except
exception
as ex:
print ex
connect.rollback()
cursor.close()
connect.close()
#查詢示例
#插入示例
#insert(host="172.16.3.38",password="123456",db="pytester",sql="insert into pybug_pybugs(title,content) values(%s,%s)",value=(("abc","efg"),("qwe","wwww")))
#更新和刪除示例
#updanddel(host="172.16.3.38",password="123456",db="pytester",sql="update pybug_pybugs set title='***x1' where id=33")
#多個sql作為乙個事務示例
#multisql(host="172.16.3.38",password="123456",db="pytester",sqllist=["update pybug_pybugs set title='***x1' where id=33","update pybug_pybugs set title='***x1' where id=31"])
#儲存過程示例
#procedure(host="172.16.3.38",password="123456",db="pytester",procename="test1",para=("wowo","haha"))
python操作mysql查詢資料
首先需要連線資料庫,然後才查詢出資料。例如下表名字為 sinauser iduse id use name11 db12 2db233 db3class database def init self self.conn mysqldb.connect 連線資料庫 host 連線你要取出資料庫的ip,...
python操作MySQL資料庫
堅持每天學一點,每天積累一點點,作為自己每天的業餘收穫,這個文章是我在吃飯的期間寫的,利用自己零散的時間學了一下python操作mysql,所以整理一下。我採用的是mysqldb操作的mysql資料庫。先來乙個簡單的例子吧 import mysqldb try conn mysqldb.connec...
python操作mysql資料庫
電腦系統版本選擇,這裡安裝過程就不具體描述了,現在來具體說下python操作mysql資料庫進行簡單的增刪改查操作.talk is cheap,show you code 下面就開始寫 usr local bin env python coding utf 8 python連線mysql資料庫和se...