1. 程式人生 > >MySQL與Python交互

MySQL與Python交互

turn res 方式 etc 關閉 .com elf products from

sudo apt-get install python-mysql

假設有一數據庫test1,裏面有一張產品信息表products,向其中插入一條產品信息,程序如下:

# -*- coding: utf-8 -*-
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)
cs1=conn.cursor()
count=cs1.execute("insert into products(prod_name) values(‘iphone‘)")
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message

Connection對象:用於建立與數據庫的連接
創建對象:調用connect()方法
conn=connect(參數列表)
參數host:連接的mysql主機,如果本機是‘localhost‘
參數port:連接的mysql主機的端口,默認是3306
參數db:數據庫的名稱
參數user:連接的用戶名
參數password:連接的密碼
參數charset:通信采用的編碼方式,默認是‘gb2312‘,要求與數據庫創建時指定的編碼一致,否則中文會亂碼

對象的方法
close()關閉連接
commit()事務,所以需要提交才會生效
rollback()事務,放棄之前的操作
cursor()返回Cursor對象,用於執行sql語句並獲得結果

Cursor對象:執行sql語句
創建對象:調用Connection對象的cursor()方法
cursor1=conn.cursor()

對象的方法
close()關閉
execute(operation [, parameters ])執行語句,返回受影響的行數
fetchone()執行查詢語句時,獲取查詢結果集的第一個行數據,返回一個元組
next()執行查詢語句時,獲取當前行的下一行
fetchall()執行查詢時,獲取結果集的所有行,一行構成一個元組,再將這些元組裝入一個元組返回
scroll(value[,mode])將行指針移動到某個位置
mode表示移動的方式
mode的默認值為relative,表示基於當前行移動到value,value為正則向下移動,value為負則向上移動
mode的值為absolute,表示基於第一條數據的位置,第一條數據的位置為0

修改/刪除

# -*- coding: utf-8 -*-
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)
cs1=conn.cursor()
# 修改
count=cs1.execute("update products set prod_name=‘xiaomi‘ where id=6")
   # 刪除
  count=cs1.execute("delete from products where id=6")
  print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message

插入一條數據

# -*- coding: utf-8 -*-
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)
cs1=conn.cursor()
prod_name=raw_input("請輸入產品名稱:")
params=[prod_name]
count=cs1.execute(‘insert into products(sname) values(%s)‘,params)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message

查詢一條

# -*- coding: utf-8 -*-
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)
cs1=conn.cursor()
cur.execute(‘select * from products where id=2‘)
result=cur.fetchone()
print result
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message

查詢多條

# -*- coding: utf-8 -*-
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘test1‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)
cs1=conn.cursor()
cur.execute(‘select * from prod_name‘)
result=cur.fetchall()
print result
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message

封裝:觀察前面的程序發現,除了sql語句及參數不同,其它語句都是一樣的,可以進行封裝然後調用

# -*- coding: utf-8 -*-
import MySQLdb

class MysqlHelper():
def __init__(self,host,port,db,user,passwd,charset=‘utf8‘):
self.host=host
self.port=port
self.db=db
self.user=user
self.passwd=passwd
self.charset=charset

def connect(self):
self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
self.cursor=self.conn.cursor()

def close(self):
self.cursor.close()
self.conn.close()

def get_one(self,sql,params=()):
result=None
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchone()
self.close()
except Exception, e:
print e.message
return result

def get_all(self,sql,params=()):
list=()
try:
self.connect()
self.cursor.execute(sql,params)
list=self.cursor.fetchall()
self.close()
except Exception,e:
print e.message
return list

def insert(self,sql,params=()):
return self.__edit(sql,params)

def update(self, sql, params=()):
return self.__edit(sql, params)

def delete(self, sql, params=()):
return self.__edit(sql, params)

def __edit(self,sql,params):
count=0
try:
self.connect()
count=self.cursor.execute(sql,params)
self.conn.commit()
self.close()
except Exception,e:
print e.message
return count

保存為MysqlHelper.py文件

# -*- coding: utf-8 -*-
from MysqlHelper import *

sql=‘insert intoproducts(prod_name,price) values(%s,%s)‘
prod_name=raw_input("請輸入產品名稱:")
price=raw_input("請輸入單價:")
params=[prod_name,price]

mysqlHelper=MysqlHelper(‘localhost‘,3306,‘test1‘,‘root‘,‘mysql‘)
count=mysqlHelper.insert(sql,params)
if count==1:
print ‘ok‘
else:
print ‘error‘

調用類查詢查詢

# -*- coding: utf-8 -*-
from MysqlHelper import *

sql=‘select prod_name,price from products order by id ‘

helper=MysqlHelper(‘localhost‘,3306,‘test1‘,‘root‘,‘mysql‘)
one=helper.get_one(sql)
print one

MySQL與Python交互