python mysql 封裝

2022-09-22 08:27:20 字數 3253 閱讀 9730

#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,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

新增

#encoding=utf8

from mysqlhelper import *

sql='insert into students(sname,gender) values(%s,%s)'

sname=raw_input("請輸入使用者名稱:")

gender=raw_input("請輸入性別,1為男,0為女")

params=[sname,bool(gender)]

mysqlhelper=mysqlhelper('localhost',3306,'test1','root','mysql')

count=mysqlhelper.insert(sql,params)

if count==1:

print 'ok'

else:

print 'error'

查詢一個

#encoding=utf8

from mysqlhelper import *

sql='select sname,gender from students order by id desc'

helper=mysqlhelper('localhost',3306,'test1','root','mysql')

one=helper.get_one(sql)

print one

建立使用者表userinfos

注意:需要對密碼進行加密

如果使用md5加密,則密碼包含32個字元

如果使用sha1加密,則密碼包含40個字元,推薦使用這種方式

create table userinfos(

id int primary key auto_increment,

uname varchar(20),

upwd char(40),

isdelete bit default 0

);

加入測試資料

insert into userinfos values(0,'123','40bd001563085fc35165329ea1ff5c5ecbdbbeef',0);

接收輸入並驗證
#encoding=utf-8

from mysqlhelper import mysqlhelper

from hashlib import sha1

sname=raw_input("請輸入使用者名稱:")

spwd=raw_input("請輸入密碼:")

s1=sha1()

s1.update(spwd)

spwdsha1=s1.hexdigest()

sql="select upwd from userinfos where uname=%s"

params=[sname]

sqlhelper=mysqlhelper('localhost',3306,'test1','root','mysql')

userinfo=sqlhelper.get_one(sql,params)

if userinfo==none:

print '使用者名稱錯誤'

elif userinfo[0]==spwdsha1:

print '登入成功'

else:

print '密碼錯誤'

python操作mysql

安裝 python操作mysql資料庫,主要就是通過pymysql模組 pip install pymysql操作流程 1 建立資料庫連線物...

Python操作MySql

一 linux客戶端連線mssql server 1 linux下安裝unixodbc 2 linux安裝freetds 1 配置freet...

Python MySQL操作

python mysql操作 2014 08 06 一 安裝setuptools wget tar zxvf setuptools 0 6c11 tar gz cd setuptools 0 6c11 python setup py build python setup py install 二 安...