#coding=gbk
#pip install pymysql
import pymysql
host = "127.0.0.1"
user = "root"
password = "123654"
port = 3306
database = "test"
charset = "utf8"
#获取数据库连接
def GetConn():
conn = pymysql.connect(host=host,user=user,password=password,database=database,port=port,charset=charset,cursorclass=pymysql.cursors.DictCursor)
return conn
#执行简单查询
def Query(sql):
conn = GetConn()
cursor = conn.cursor()
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
conn.close()
return result
#执行带参数的查询
def QueryWithParms(sql,parms):
conn = GetConn()
cursor = conn.cursor()
cursor.execute(sql,parms)
result = cursor.fetchall()
cursor.close()
conn.close()
return result
#执行简单SQL
def ExecSQL(sql):
conn = GetConn()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
return cursor.rowcount
#执行带参数的SQL
def ExecSQLWithParms(sql,parms):
conn = GetConn()
cursor = conn.cursor()
cursor.execute(sql,parms)
conn.commit()
cursor.close()
conn.close()
return cursor.rowcount
#执行多参数的SQL
def ExecSQLMany(sql,parms):
conn = GetConn()
cursor = conn.cursor()
cursor.executemany(sql,parms)
conn.commit()
cursor.close()
conn.close()
return cursor.rowcount
#调用事例
# import MySQLHelper
# import datetime
#执行简单查询和带参数的查询
# result = MySQLHelper.Query("select * from t1 where id = 1")
# result = MySQLHelper.Query("select * from t1 where name like '%张%'")
# result = MySQLHelper.QueryWithParms("select * from t1 where name like %s",'%张%')
# result = MySQLHelper.QueryWithParms("select * from t1 where id = %s",1)
# result = MySQLHelper.QueryWithParms("select * from t1 where id in (%s,%s,%s,%s)",(2,3,4,5))
# for row in result:
# print(row["id"])
# print(row["name"])
# print(datetime.datetime.strftime(row["addtime"],"%F %T"),"\n")
#执行简单SQL
# row = MySQLHelper.ExecSQL("insert into t1(name,addtime) values('小丁','2018-09-18')")
# print(row)
#执行带参数的SQL
# parms = ('韩梅梅','2018-09-18')
# row = MySQLHelper.ExecSQLWithParms("insert into t1(name,addtime) values(%s,%s)",parms)
# print(row)
#执行多参数的SQL
# parms = (('雷锋','2018-09-18'),('小丁','2018-09-19'),('小胡','2018-09-20'))
# row = MySQLHelper.ExecSQLMany("insert into t1(name,addtime) values(%s,%s)",parms)
# print(row)
源码下载:MySQLHelper.zip
ok
mjj通道