import pymysql
from pymysql.cursors import DictCursorfrom pymysql import cursorsdef creat_conn(): conn=pymysql.connect( user=‘root’, password=‘123456’, host=‘localhost’, database=‘spider’,
port=3306, )
return conn
def change(sql,isinsert=‘false’):
try:
conn=creat_conn() cursor=conn.cursor(cursor=DictCursor) count=cursor.execute(sql) conn.commit()
if isinsert==‘true’:
return cursor.lastrowid
else:
return count
except Exception as err:
print(err)
conn.rollback()
finally:
if cursor:
cursor.close()
if conn:
conn.close()
def add(sql): change(sql,isinsert=‘true’)
def upd(sql): change(sql,isinsert=‘false’)
def delete(sql): change(sql,isinsert=‘false’)
def get_one(sql):
try: conn = creat_conn()
cursor = conn.cursor(cursor=DictCursor)
count = cursor.execute(sql) info=cursor.fetchone()
print(info)
except Exception as err: print(err)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
def get_all(sql):
try: conn = creat_conn() cursor = conn.cursor(cursor=DictCursor) count = cursor.execute(sql) info=cursor.fetchall()
print(info)
except Exception as err: print(err)
finally:
if cursor: cursor.close()
if conn: conn.close()
if name==‘main’: sql=“insert into test_table(name,gender,age)values(‘heting’,‘nv’,‘30’)”
add(sql)
用python实现从mysql的增删改查代码
最新推荐文章于 2024-04-06 19:37:00 发布