1. 程式人生 > >python3 操作mysql資料庫

python3 操作mysql資料庫

著急下班,直接上程式碼,有時間回來補充說明:

pymysql 為第三方包,使用前需要自行安裝,我直接聯網安裝的,當然,也可以使用原始碼安裝,根據個人情況而定。

pymysql 主要步驟為:1. 得到連結,拿到遊標(通過連結,得到cursor()),

2. 通過cursor,呼叫execute方法執行sql語句,

3. 若查詢數,則通過fetchall()(得到所有資料),fetchone()(得到1條資料)fetchmany()(得到指定條數,資料),

4. 其他的就是有關關閉遊標,關閉資料庫連結,提交資料,回滾資料,方法如下:

cursor.close()(關閉遊標),conn.close()(關閉書庫連結),conn.commit()(提交更改,刪除和更新資料時候用到),conn.rollbak()(回滾資料,刪除和更新時候用到。)

pip install pymysql 安裝pymysql模組

程式碼如下:

  1 # -*- coding: utf-8 -*-
  2 """
  3 Created on Tue Dec 18 09:26:52 2018
  4 
  5 @author: 
  6 """
  7 
  8 import pymysql
  9 
 10 #得到資料庫連結
 11 def getConnMySQL(host,port,user,password,db,charset):
 12     global MysqlConn
 13     try:
 14         MysqlConn = pymysql.connect(host = host,
15 port = int(port), 16 user = user, 17 password = password, 18 db = db, 19 charset = charset) 20 except: 21 print
('connect database failed') 22 exit(1) 23 24 #建立表 25 def createTable(): 26 try: 27 with MysqlConn.cursor() as cursor: 28 dropsql = '''drop table if exists student;''' 29 cursor.execute(dropsql) 30 createsql = ''' 31 create table student 32 (id VARCHAR(20) COMMENT 'id', 33 sname VARCHAR(20) COMMENT '姓名', 34 sex VARCHAR(2) comment '性別', 35 age VARCHAR(20) comment '年齡' 36 ) 37 ENGINE=INNODB DEFAULT CHARSET = utf8; 38 ''' 39 b = cursor.execute(createsql) 40 print(b) 41 42 except Exception as e: 43 print(e) 44 finally: 45 cursor.close() 46 47 #插入資料 48 def insertData(): 49 ids = '3' 50 sname = '韓紅' 51 sex = '' 52 age = '26' 53 54 try: 55 with MysqlConn.cursor() as cursor: 56 #定義插入語句 57 insertsql = """insert into student(id,sname,sex,age) 58 values('%s','%s','%s','%s') """% \ 59 (ids,sname,sex,age) 60 #執行插入語句 61 cursor.execute(insertsql) 62 #資料庫提交 63 MysqlConn.commit() 64 except Exception as e: 65 MysqlConn.rollback() 66 print(e) 67 finally: 68 cursor.close() 69 70 #刪除資料 71 def deleteData(): 72 try: 73 with MysqlConn.cursor() as cursor: 74 delsql = "delete from student where id = %s"%(3) 75 #執行sql 76 cursor.execute(delsql) 77 #提交 78 MysqlConn.commit() 79 except Exception as e: 80 print(e) 81 #失敗回滾 82 MysqlConn.rollback() 83 finally: 84 cursor.close() 85 86 #更新資料 87 def upadteData(): 88 try: 89 with MysqlConn.cursor() as cursor: 90 updatesql = "update student set id = '%s' where id = '%s' \ 91 and age = '%s'"% (4,3,26) 92 #執行sql 93 cursor.execute(updatesql) 94 #提交 95 MysqlConn.commit() 96 except Exception as e: 97 print(e) 98 #失敗則回滾 99 MysqlConn.rollback() 100 finally: 101 cursor.close() 102 103 #fetchone通過查詢,得到一條資料 104 def queryDataOne(): 105 try: 106 with MysqlConn.cursor() as cursor: 107 #定義查詢sql 108 querysql = 'select id,sname,sex,age from student;' 109 #執行sql 110 count = cursor.execute(querysql) 111 #簡單邏輯,若有需要則在邏輯內加內容 112 if count <=0: 113 print("not data") 114 elif count > 0: 115 #得到一條資料 116 result = cursor.fetchone() 117 #此處返回值為一個元組,要得到具體的值,轉為列表,根據索引取值 118 print(type(result)) 119 reslist = list(result) 120 ids = reslist[0] 121 sname = reslist[1] 122 sex = reslist[2] 123 age = reslist[3] 124 print(ids,sname,sex,age) 125 else: 126 pass 127 except Exception as e: 128 print(e) 129 finally: 130 cursor.close() 131 132 #得到所查詢出來的全部資料 133 def queryDataAll(): 134 try: 135 with MysqlConn.cursor() as cursor: 136 querysql = 'select id,sname,sex,age from student;' 137 sqlQuerycnt = cursor.execute(querysql) 138 if sqlQuerycnt <= 0: 139 print('table is empty') 140 elif sqlQuerycnt > 0: 141 res = cursor.fetchall() 142 print(type(res)) 143 for rows in list(res): 144 print('ids = ' + rows[0]) 145 else: 146 pass 147 except Exception as e: 148 print(e) 149 finally: 150 cursor.close() 151 152 #獲取前N行資料,若庫中沒有那麼多資料,則有多少取多少。 153 def queryDataMany(): 154 try: 155 with MysqlConn.cursor() as cursor: 156 quersql = 'select id,sname,sex,age from student;' 157 querCnt = cursor.execute(quersql) 158 if querCnt <= 0 : 159 print('table is empty') 160 elif querCnt > 0: 161 res = cursor.fetchmany(10) 162 # 返回元組(多行情況下,為雙重元組,也就是巢狀關係) 163 # 根據需求,來指定具體取幾條,然後再確定邏輯 164 print(type(res)) 165 print(res) 166 else: 167 pass 168 except Exception as e: 169 print(e) 170 finally: 171 cursor.close() 172 173 if __name__ == '__main__': 174 175 #此處可以寫個配置檔案,通過讀取配置檔案的方式來得到這些引數,不宜寫死。 176 host = '192.168.2.2' 177 port = '3306' 178 user = 'root' 179 password = '123456' 180 db = 'mysql' 181 charset = 'utf8' 182 #連結資料庫 183 getConnMySQL(host,port,user,password,db,charset) 184 #建立表 185 createTable() 186 #插入資料 187 insertData() 188 #刪除資料 189 deleteData() 190 #更新資料 191 upadteData() 192 #查詢一條資料 193 queryDataOne() 194 #查詢全部資料 195 queryDataAll() 196 #得到指定條數資料 197 queryDataMany() 198 #關閉資料庫連結 199 MysqlConn.close() 200