1、環境數據准備:
python3環境、pymysql模塊
mysql數據庫:本次代碼中用到的數據庫為本地的testdb數據庫,user表(表字段比較簡單,只有主鍵id,手機號mobile,密碼passwd)
2、本次代碼直接封裝為類,代碼中附有注釋,把數據庫參數改為自己實際的就可以直接使用
1 #引入pymysql模塊 2 import pymysql 3 4 class DoMysql: 5 #初始化 6 def __init__(self): 7 #創建連接 8 self.conn = pymysql.Connect( 9 host = 'localhost', 10 port = 3306, 11 user = 'root', 12 password = 'root', 13 db = 'testdb', 14 charset = 'utf8', 15 cursorclass = pymysql.cursors.DictCursor #以字典的形式返回數據 16 ) 17 #獲取游標 18 self.cursor = self.conn.cursor() 19 20 #返回多條數據 21 def fetchAll(self,sql): 22 self.cursor.execute(sql) 23 return self.cursor.fetchall() 24 25 #插入一條數據 26 def insert_one(self,sql): 27 result = self.cursor.execute(sql) 28 self.conn.commit() 29 return result 30 31 #插入多條數據 32 def insert_many(self,sql,datas): 33 result = self.cursor.executemany(sql,datas) 34 self.conn.commit() 35 return result 36 37 #更新數據 38 def update(self,sql): 39 result = self.cursor.execute(sql) 40 self.conn.commit() 41 return result 42 43 #關閉連接 44 def close(self): 45 self.cursor.close() 46 self.conn.close() 47 48 49 50 51 if __name__ == '__main__': 52 mysql = DoMysql() 53 #插入一條數據 54 sql = 'insert into `user`(`mobile`,`passwd`) values("13100010000","123456")' 55 result = mysql.insert_one(sql) 56 print(result) #返回插入數據的條數(1) 57 58 #插入多條數據 59 datas = [ 60 ("13100010001","111111"), 61 ("13100010002","666666") 62 ] 63 sql = 'insert into `user`(`mobile`,`passwd`) values(%s,%s)' 64 result = mysql.insert_many(sql,datas) 65 print(result) #返回插入數據的條數(2) 66 67 #查詢數據 68 sql = 'select * from user' 69 result = mysql.fetchAll(sql) #返回列表,如果多條數據,列表中嵌套字典 70 for item in result: 71 print(item.get('mobile')) #循環列表,輸出mobile值 72 73 #關閉連接 74 mysql.close()
3、擴展信息
pymysql.Connect()參數說明
host(str): MySQL服務器地址
port(int): MySQL服務器端口號
user(str): 用戶名
passwd(str): 密碼
db(str): 數據庫名稱
charset(str): 連接編碼
connection對象支持的方法
cursor() 使用該連接創建並返回游標
commit() 提交當前事務
rollback() 回滾當前事務
close() 關閉連接
cursor對象支持的方法
execute(op) 執行一個數據庫的查詢命令
fetchone() 取得結果集的下一行
fetchmany(size) 獲取結果集的下幾行
fetchall() 獲取結果集中的所有行
rowcount() 返回數據條數或影響行數
close() 關閉游標對象