import pymysql # 查 所數據 def get_all(sql): conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.execute(sql) res = cur.fetchall() cur.close() conn.close() return res # 查 一行數據 def get_one(sql,args): conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.execute(sql,args) res = cur.fetchone() cur.close() conn.close() return res # 增 刪 改 都要提交 commit def get_mif(sql,args): conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.execute(sql,args) conn.commit() cur.close() conn.close() # 增 刪 改 都要提交 commit # 添加而且帶返回值 def get_create(sql,args): conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.execute(sql,args) conn.commit() cur.close() conn.close() return cur.lastrowid # python插入記錄後取得主鍵id的方法(cursor.lastrowid和conn.insert_id()) # 增 刪 改 都要提交 commit # 批量加入 以元祖的形式傳參數 就是添加幾回次提交一次 def mul_mode(sql, args): conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # self.cursor.executemany("insert into user (id,name) values (%s,%s)",[(1,"aaa"),(2,"bbb"),(3,"ccc")]) 傳參方式 cur.executemany(sql, args) conn.commit() cur.close() conn.close()
import pymysql # 注意 args 參數能夠傳空值[] class Mysqls(object): def __init__(self): # 讀取配置文件 self.connect() def connect(self): self.conn = pymysql.connect(host="localhost", user="root", password="root", database="db6") # 能夠把主機鏈接等寫入配置文件 等 self.cursor=self.conn.cursor(cursor=pymysql.cursors.DictCursor) # 獲取因此數據 def get_all(self,sql,args): self.cursor.execute(sql,args) res = self.cursor.fetchall() return res # 獲取一行數據 def get_one(self,sql,args): self.cursor.execute(sql, args) res = self.cursor.fetchone() return res # 添加 就是添加一次提交屢次 def get_mode (self,sql,args): self.cursor.execute(sql, args) self.conn.commit() # 添加而且帶返回值 def get_create(self,sql,args): self.cursor.execute(sql,args) self.conn.commit() return self.cursor.lastrowid # python插入記錄後取得主鍵id的方法(cursor.lastrowid和conn.insert_id()) # 批量加入 以元祖的形式傳參數 就是添加一次提交一次 def mul_mode(self, sql, args): # self.cursor.executemany("insert into user (id,name) values (%s,%s)",[(1,"aaa"),(2,"bbb"),(3,"ccc")]) 傳參方式 self.cursor.executemany(sql, args) self.conn.commit() def get_close(self): self.cursor.close() self.conn.close()