pymysql連接數據庫,實現數據庫增刪改查
阿新 • • 發佈:2019-01-14
commit any fault 更改 com null primary div mar
1.數據庫連接
# 創建連接 def create_conn(): import pymysql conn = pymysql.connect( host=‘localhost‘, port=3306, user=‘root‘, password=‘root‘, database=‘py‘, charset=‘utf8‘ ) # 得到一個可以執行SQL語句並且將結果作為字典返回的遊標 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)return conn, cursor
# 關閉連接 def close_conn(conn, cursor): # 關閉光標對象 cursor.close() # 關閉數據庫連接 conn.close()
2.增
# 單條插入數據 def InsertOneDB(sql, data): conn, cursor = create_conn() cursor.executemany(sql, data) conn.commit() close_conn(conn, cursor) sqlInsertOneDB= "insert into user444 (name,age) values (%s,%s);" data = [(‘john‘, 26)] InsertOneDB(sqlInsertOneDB, data)
# 批量添加數據 def InsertManyDB(sql, data): conn, cursor = create_conn() cursor.executemany(sql, data) conn.commit() close_conn(conn, cursor) data = [ (‘apollo‘, ‘28‘), (‘jack‘, ‘21‘), (‘merry‘, ‘29‘) ] sql = ‘insert into user444(name,age) values(%s,%s);‘ InsertManyDB(sql, data)
3.刪
# 刪除數據 def DeleteOneDB(sql, data): conn, cursor = create_conn() print(sql) cursor.execute(sql, data) conn.commit() close_conn(conn, cursor) # 定義將要執行的SQL語句 sql = "delete from user333 where name=%s;" data = [("apollo11")] DeleteOneDB(sql, data)
4.改
# 更改數據 def UpdataOneDB(sql, data): conn, cursor = create_conn() print(sql) cursor.execute(sql, data) conn.commit() close_conn(conn, cursor) sql = "update user333 set name=%s where name=%s;" data = [‘Lily‘, ‘jack11‘] UpdataOneDB(sql, data)
5.查
# 查詢數據 def SelectDB(sql, action, limit=None): conn, cursor = create_conn() cursor.execute(sql) if action == ‘fetchone‘: ret = cursor.fetchone() # 取一條 elif action == ‘fetchmany‘ and limit != None: ret = cursor.fetchmany(limit) # 取三條 else: ret = cursor.fetchall() # 取全部 for item in ret: print(item) close_conn(conn, cursor) # 執行查詢的sql語句 sql = "select name,age from user333;" # action可選值:fetchone,fetchmany,fetchall # fetchmany必須提供limit參數 action = ‘fetchmany‘ # 取數據庫前3條數據 SelectDB(sql, action, 3) # fetchall取所有數據 SelectDB(sql, action) # fetchone取一條數據 SelectDB(sql, action)
6.創建表SQL
create table userinfo( id int auto_increment primary key , name varchar(32) not null unique , age int(2) )engine =innodb default charset = utf8; #註意:charset=‘utf8‘ 不能寫成utf-8
pymysql連接數據庫,實現數據庫增刪改查