pymysql連線資料庫,實現資料庫增刪改查
阿新 • • 發佈:2019-01-14
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