【Python學習之十】操做數據庫

環境
  虛擬機:VMware 10
  Linux版本:CentOS-6.5-x86_64
  客戶端:Xshell4
  FTP:Xftp4
  python3.6java

操做mysql數據庫python

一、安裝pymysql模塊
pip install pymysql
或者
conda install pymysqlmysql

二、使用示例 sql

相對java 是很是簡單的shell

'''
Created on 2019年5月8日

@author: Administrator
'''
import pymysql as db
#建立鏈接
conn=db.connect('134.32.123.101','root','123456','spark')
#獲取遊標
cursor=conn.cursor()
#遊標執行語句
cursor.execute('select * from person')
#獲取一條記錄
pn=cursor.fetchone()
print(pn)#結果是一個元組:('1', 'zhangsan', 18)
#獲取全部元素
pns=cursor.fetchall()
print(pns)#(('2', 'wangwu', 12), ('3', 'lisi', None))
#關閉鏈接
conn.close()

三、數據庫操做工具類數據庫

#coding:utf-8
import  pymysql

class MysqlHelper(object):
    config={
        "host":"localhost",
        "user":"root",
        "password":"123456",
        "db":"demo",
        "charset":"utf8"
    }
    def __init__(self):
        self.connection=None
        self.cursor=None

    # 從數據庫表中查詢一行數據 select count(*) from emp
    def getOne(self,sql,*args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql,args)
            return self.cursor.fetchone()
        except Exception as ex:
            print(ex,ex)
        finally:
            self.close()

    # 從數據庫表中查詢多行數據
    def getList(self,sql,*args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql,args)
            return self.cursor.fetchall()
        except Exception as ex:
            print(ex,ex)
        finally:
            self.close()

    # 對數據庫進行增,刪,改
    def executeDML(self,sql,*args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql,args)#  返回 sql語句執行以後影響的行數
            new_id = self.connection.insert_id() # 返回系統剛剛自動生成的id
            self.connection.commit();
            return new_id
        except Exception as ex:
            self.connection.rollback()
            print(ex,ex)
        finally:
            self.close()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

if __name__ == "__main__":
    helper = MysqlHelper()
    print(helper.executeDML("delete from dept where deptno=%s",80))
#     print(helper.executeDML("insert into dept values(%s,%s,%s)","80","admin","beijing"))

 

參考:
Python學習筆記工具

相關文章
相關標籤/搜索