1. 程式人生 > >python & MySQLdb(Three)

python & MySQLdb(Three)

#實現python封裝
# encoding=utf8
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,param=()):
        result=None
        try:
            self.connect()
            self.cursor.execute(sql,param)
            result=self.cursor.fetchone()
            self.close()
        except Exception as e:
            print(e)
        return result
    #查詢一行
def get_all(self,sql,param=()):
        list=()
        try:
            self.connect()
            self.cursor.execute(sql,param)
            list=self.cursor.fetchall()
            self.close()
        except Exception as e:
             print(e)
        return list
    #查詢全部資料
def insert(self,sql,param=()):
        return self.__edit(sql,param)
    #返回插入資料
def update(self,sql,param):
        return self.__edit(sql,param)
    #返回更改後資料
def delete(self,sql,param):
        return self.__edit(sql,param)
    #返回刪除資料
def __edit(self,sql,param):
        count=0
        try:
            self.connect()
            count=self.cursor.execute(sql,param)
            self.conn.commit()
            self.close()
        except Exception as e:
            print(e)
        return count
實現新增操作:
#encoding=utf8
from fengzhaung import *
sql="insert into stu(stu_name,stu_hometown,gender) values(%s,%s,%s)"
stu_name=input("輸入姓名")
stu_hometown=input("請輸入家鄉:")
gender=input("輸入性別,1男,0女:")
param=[stu_name,stu_hometown,bool(gender)]
mysqlh=MysqlHelper('192.168.65.146',3306,'student','root','toor')
count=mysqlh.insert(sql,param)
if count==1:
    print ('ok')
else:
    print('error')
實現查詢:
#encoding=utf8
from fengzhaung import *
#id=input("輸入編號")
sql="select * from stu where stu_id=1"
helper=MysqlHelper('192.168.65.146',3306,'student','root','toor')
s=helper.get_one(sql)
print(s)
最後還有一點小問題,怎麼自主輸入進行查詢??試了幾種辦法,發現不行。

  

 

mmp我搞了半天發現是在做字串的轉換,這個是必然報錯的,但是我們用連線操作就可以了,利用MySQLhelper的get_one方法去傳就可以了,自己真的菜啊看來

#方法一:
#encoding=utf8
from fengzhaung import *
ih=input("輸入編號")
print(id(ih))
sql="select * from stu where stu_id="+ih
helper=MysqlHelper('192.168.65.146',3306,'student','root','toor')
s=helper.get_one(sql)
print(s)
#方法二
#encoding=utf8
from fengzhaung import *
ih=input("請輸入編號:")
sql="select * from stu where stu_id=%s"
param=[ih]
helper=MysqlHelper('192.168.65.146',3306,'student','root','toor')
s=helper.get_one(sql,param)
print(s)