mysql與python交互(二)

增加

  • 創(chuàng)建testInsert.py文件,向?qū)W生表中插入一條數(shù)據(jù)
import pymysql
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 as e:
    print(e)

修改

  • 創(chuàng)建testUpdate.py文件,修改學(xué)生表的一條數(shù)據(jù)
import pymysql
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 as e:
    print(e)

刪除

  • 創(chuàng)建testDelete.py文件,刪除學(xué)生表的一條數(shù)據(jù)
import pymysql
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 as e:
    print(e)

sql語句參數(shù)化

  • 創(chuàng)建testInsertParam.py文件,向?qū)W生表中插入一條數(shù)據(jù)
import pymysql
try:
 conn=MySQLdb.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8')
    cs1=conn.cursor()
    sname=raw_input("請輸入學(xué)生姓名:")
    params=[sname]
    count=cs1.execute('insert into students(sname) values(%s)',params)
    print(count)
    conn.commit()
    cs1.close()
    conn.close()
except Exception as e:
    print(e)

其它語句

  • cursor對象的execute()方法,也可以用于執(zhí)行create table等語句

  • 建議在開發(fā)之初,就創(chuàng)建好數(shù)據(jù)庫表結(jié)構(gòu),不要在這里執(zhí)行

查詢一行數(shù)據(jù)

  • 創(chuàng)建testSelectOne.py文件,查詢一條學(xué)生信息
import pymysql
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 as e:
    print(e)

查詢多行數(shù)據(jù)

  • 創(chuàng)建testSelectMany.py文件,查詢一條學(xué)生信息
import pymysql
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 as e:
    print(e)

封裝

  • 觀察前面的文件發(fā)現(xiàn),除了sql語句及參數(shù)不同,其它語句都是一樣的

  • 創(chuàng)建MysqlHelper.py文件,定義類

import pymysql
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 as e:
            print(e)
        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 as e:
            print(e)
        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 as e:
            print(e)
        return count

添加

  • 創(chuàng)建testInsertWrap.py文件,使用封裝好的幫助類完成插入操作
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')

查詢一個

  • 創(chuàng)建testGetOneWrap.py文件,使用封裝好的幫助類完成查詢最新一行數(shù)據(jù)操作
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)


---

### 結(jié)束語
如果您對這篇文章有什么意見或者建議,請評論與我討論.
如果您覺得還不錯的話~可以點(diǎn)個喜歡鼓勵我哦.
如果您想和我一起學(xué)習(xí),請毫不吝嗇的私信我吧~
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容