日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

如何使用Python操作MySQL数据库

發(fā)布時(shí)間:2024/7/23 数据库 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使用Python操作MySQL数据库 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

安裝引入模塊
安裝mysql模塊
sudo apt-get install python-mysql

在文件中引入模塊
import Mysqldb

Connection對(duì)象
用于建立與數(shù)據(jù)庫(kù)的連接
創(chuàng)建對(duì)象:調(diào)用connect()方法
conn=connect(參數(shù)列表)
參數(shù)host:連接的mysql主機(jī),如果本機(jī)是’localhost’
參數(shù)port:連接的mysql主機(jī)的端口,默認(rèn)是3306
參數(shù)db:數(shù)據(jù)庫(kù)的名稱(chēng)
參數(shù)user:連接的用戶(hù)名
參數(shù)password:連接的密碼
參數(shù)charset:通信采用的編碼方式,默認(rèn)是’gb2312’,要求與數(shù)據(jù)庫(kù)創(chuàng)建時(shí)指定的編碼一致,否則中文會(huì)亂碼

對(duì)象的方法
close()關(guān)閉連接
commit()事務(wù),所以需要提交才會(huì)生效
rollback()事務(wù),放棄之前的操作
cursor()返回Cursor對(duì)象,用于執(zhí)行sql語(yǔ)句并獲得結(jié)果
Cursor對(duì)象

執(zhí)行sql語(yǔ)句
創(chuàng)建對(duì)象:調(diào)用Connection對(duì)象的cursor()方法
cursor1=conn.cursor()

對(duì)象的方法
close()關(guān)閉
execute(operation [, parameters ])執(zhí)行語(yǔ)句,返回受影響的行數(shù)
fetchone()執(zhí)行查詢(xún)語(yǔ)句時(shí),獲取查詢(xún)結(jié)果集的第一個(gè)行數(shù)據(jù),返回一個(gè)元組
next()執(zhí)行查詢(xún)語(yǔ)句時(shí),獲取當(dāng)前行的下一行
fetchall()執(zhí)行查詢(xún)時(shí),獲取結(jié)果集的所有行,一行構(gòu)成一個(gè)元組,再將這些元組裝入一個(gè)元組返回
scroll(value[,mode])將行指針移動(dòng)到某個(gè)位置
mode表示移動(dòng)的方式
mode的默認(rèn)值為relative,表示基于當(dāng)前行移動(dòng)到value,value為正則向下移動(dòng),value為負(fù)則向上移動(dòng)
mode的值為absolute,表示基于第一條數(shù)據(jù)的位置,第一條數(shù)據(jù)的位置為0

對(duì)象的屬性
rowcount只讀屬性,表示最近一次execute()執(zhí)行后受影響的行數(shù)
connection獲得當(dāng)前連接對(duì)象

增加
創(chuàng)建testInsert.py文件,向?qū)W生表中插入一條數(shù)據(jù)

#encoding=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 students(sname) values(‘張良’)”)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 count=cs1.execute(“insert into students(sname) values(‘張良’)”)7 print count8 conn.commit()9 cs1.close()10 conn.close()11except Exception,e:12 print e.message

修改
創(chuàng)建testUpdate.py文件,修改學(xué)生表的一條數(shù)據(jù)

#encoding=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 students set sname=‘劉邦’ where id=6”)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 count=cs1.execute(“update students set sname=‘劉邦’ where id=6”)7 print count8 conn.commit()9 cs1.close()10 conn.close()11except Exception,e:12 print e.message

刪除
創(chuàng)建testDelete.py文件,刪除學(xué)生表的一條數(shù)據(jù)

#encoding=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(“delete from students where id=6”)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 count=cs1.execute(“delete from students where id=6”)7 print count8 conn.commit()9 cs1.close()10 conn.close()11except Exception,e:12 print e.message

sql語(yǔ)句參數(shù)化
創(chuàng)建testInsertParam.py文件,向?qū)W生表中插入一條數(shù)據(jù)

#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cs1=conn.cursor()
sname=raw_input(“請(qǐng)輸入學(xué)生姓名:”)
params=[sname]
count=cs1.execute(‘insert into students(sname) values(%s)’,params)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx14 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 sname=raw_input(“請(qǐng)輸入學(xué)生姓名:”)7 params=[sname]8 count=cs1.execute(‘insert into students(sname) values(%s)’,params)9 print count10 conn.commit()11 cs1.close()12 conn.close()13except Exception,e:14 print e.message

其它語(yǔ)句
cursor對(duì)象的execute()方法,也可以用于執(zhí)行create table等語(yǔ)句
建議在開(kāi)發(fā)之初,就創(chuàng)建好數(shù)據(jù)庫(kù)表結(jié)構(gòu),不要在這里執(zhí)行

查詢(xún)一行數(shù)據(jù)
創(chuàng)建testSelectOne.py文件,查詢(xún)一條學(xué)生信息

#encoding=utf8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cur=conn.cursor()
cur.execute(‘select * from students where id=7’)
result=cur.fetchone()
print result
cur.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cur=conn.cursor()6 cur.execute(‘select * from students where id=7’)7 result=cur.fetchone()8 print result9 cur.close()10 conn.close()11except Exception,e:12 print e.message

查詢(xún)多行數(shù)據(jù)
創(chuàng)建testSelectMany.py文件,查詢(xún)一條學(xué)生信息

#encoding=utf8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cur=conn.cursor()
cur.execute(‘select * from students’)
result=cur.fetchall()
print result
cur.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cur=conn.cursor()6 cur.execute(‘select * from students’)7 result=cur.fetchall()8 print result9 cur.close()10 conn.close()11except Exception,e:12 print e.message

封裝
觀察前面的文件發(fā)現(xiàn),除了sql語(yǔ)句及參數(shù)不同,其它語(yǔ)句都是一樣的
創(chuàng)建MysqlHelper.py文件,定義類(lèi)

#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=Nonetry:self.connect()self.cursor.execute(sql, params)result = self.cursor.fetchone()self.close()except Exception, e:print e.messagereturn resultdef 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.messagereturn listdef 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=0try:self.connect()count=self.cursor.execute(sql,params)self.conn.commit()self.close()except Exception,e:print e.messagereturn count

xxxxxxxxxx61 1#encoding=utf82import MySQLdb3?4class MysqlHelper():5 def init(self,host,port,db,user,passwd,charset=‘utf8’):6 self.host=host7 self.port=port8 self.db=db9 self.user=user10 self.passwd=passwd11 self.charset=charset12?13 def connect(self):14 self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)15 self.cursor=self.conn.cursor()16?17 def close(self):18 self.cursor.close()19 self.conn.close()20?21 def get_one(self,sql,params=()):22 result=None23 try:24 self.connect()25 self.cursor.execute(sql, params)26 result = self.cursor.fetchone()27 self.close()28 except Exception, e:29 print e.message30 return result31?32 def get_all(self,sql,params=()):33 list=()34 try:35 self.connect()36 self.cursor.execute(sql,params)37 list=self.cursor.fetchall()38 self.close()39 except Exception,e:40 print e.message41 return list42?43 def insert(self,sql,params=()):44 return self.__edit(sql,params)45?46 def update(self, sql, params=()):47 return self.__edit(sql, params)48?49 def delete(self, sql, params=()):50 return self.__edit(sql, params)51?52 def __edit(self,sql,params):53 count=054 try:55 self.connect()56 count=self.cursor.execute(sql,params)57 self.conn.commit()58 self.close()59 except Exception,e:60 print e.message61 return count

添加
創(chuàng)建testInsertWrap.py文件,使用封裝好的幫助類(lèi)完成插入操作

#encoding=utf8
from MysqlHelper import *

sql=‘insert into students(sname,gender) values(%s,%s)’
sname=raw_input(“請(qǐng)輸入用戶(hù)名:”)
gender=raw_input(“請(qǐng)輸入性別,1為男,0為女”)
params=[sname,bool(gender)]

mysqlHelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)
count=mysqlHelper.insert(sql,params)
if count1:
print ‘ok’
else:
print ‘error’
xxxxxxxxxx14 1#encoding=utf82from MysqlHelper import *3?4sql='insert into students(sname,gender) values(%s,%s)'5sname=raw_input(“請(qǐng)輸入用戶(hù)名:”)6gender=raw_input(“請(qǐng)輸入性別,1為男,0為女”)7params=[sname,bool(gender)]8?9mysqlHelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)10count=mysqlHelper.insert(sql,params)11if count1:12 print 'ok’13else:14 print ‘error’

查詢(xún)一個(gè)
創(chuàng)建testGetOneWrap.py文件,使用封裝好的幫助類(lèi)完成查詢(xún)最新一行數(shù)據(jù)操作

#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
xxxxxxxxxx8 1#encoding=utf82from MysqlHelper import *3?4sql='select sname,gender from students order by id desc’5?6helper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)7one=helper.get_one(sql)8print one

實(shí)例:用戶(hù)登錄
創(chuàng)建用戶(hù)表userinfos
表結(jié)構(gòu)如下
id
uname
upwd
isdelete
注意:需要對(duì)密碼進(jìn)行加密
如果使用md5加密,則密碼包含32個(gè)字符
如果使用sha1加密,則密碼包含40個(gè)字符,推薦使用這種方式

create table userinfos(
id int primary key auto_increment,
uname varchar(20),
upwd char(40),
isdelete bit default 0
);
xxxxxxxxxx6 1create table userinfos(2id int primary key auto_increment,3uname varchar(20),4upwd char(40),5isdelete bit default 06);

加入測(cè)試數(shù)據(jù)
插入如下數(shù)據(jù),用戶(hù)名為123,密碼為123,這是sha1加密后的值
insert into userinfos values(0,‘123’,‘40bd001563085fc35165329ea1ff5c5ecbdbbeef’,0);
接收輸入并驗(yàn)證
創(chuàng)建testLogin.py文件,引入hashlib模塊、MysqlHelper模塊
接收輸入
根據(jù)用戶(hù)名查詢(xún),如果未查到則提示用戶(hù)名不存在
如果查到則匹配密碼是否相等,如果相等則提示登錄成功
如果不相等則提示密碼錯(cuò)誤

#encoding=utf-8
from MysqlHelper import MysqlHelper
from hashlib import sha1

sname=raw_input(“請(qǐng)輸入用戶(hù)名:”)
spwd=raw_input(“請(qǐng)輸入密碼:”)

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 ‘用戶(hù)名錯(cuò)誤’
elif userinfo[0]spwdSha1:
print ‘登錄成功’
else:
print ‘密碼錯(cuò)誤’
?x 1#encoding=utf-82from MysqlHelper import MysqlHelper3from hashlib import sha14?5sname=raw_input(“請(qǐng)輸入用戶(hù)名:”)6spwd=raw_input(“請(qǐng)輸入密碼:”)7?8s1=sha1()9s1.update(spwd)10spwdSha1=s1.hexdigest()11?12sql="select upwd from userinfos where uname=%s"13params=[sname]14?15sqlhelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)16userinfo=sqlhelper.get_one(sql,params)17if userinfoNone:18 print '用戶(hù)名錯(cuò)誤’19elif userinfo[0]==spwdSha1:20 print '登錄成功’21else:22 print ‘密碼錯(cuò)誤’
想學(xué)習(xí)交流,視頻資源等,推薦群:C++大學(xué)技術(shù)協(xié)會(huì):145655849

總結(jié)

以上是生活随笔為你收集整理的如何使用Python操作MySQL数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。