先安装pymysql pip install pymysql
一、写一个脚本:tools.py
import
pymysql
''' 1、连接数据库 2、选择数据库 3、获取游标 4、增删改查 ''' def query(sql): ''' 这是数据库的查询方法 ''' db = pymysql.connect(host="localhost",user="root",password="123456",db="testdb") cursor = db.cursor() #获取游标 cursor.execute(sql) #让游标去执行SQL语句 res = cursor.fetchall() #存储结果 db.close() #用完数据库并关闭 print(res)
aa =query("select * from t_class;")
print(aa)
bb=[]
for i in aa:
bb.append(i[1])
print(bb)
def commit(sql):
'''
这是数据库的修改方法
'''
db = pymysql.connect(host="localhost",user="root",password="123456",db="testdb")
cursor = db.cursor() #获取游标
try:
cursor.execute(sql) #让游标去执行SQL语句
db.commit() #提交结果
db.close() #用完数据库并关闭
except:
return "sql语句错误"
x = commit("insert into t_class value("5")")
#方法的定义: ''' def 方法名(参数1,参数2,或者不传参也可以): 写一些语句 最后就调用 ''' def count(value): xx = [1,2,3,4,5,5,5,5,6] x = 0 for i in xx: if i == value: x = x + 1 return x #或者可print(x) #如果上面是return x 的话,在调用完方法后是需要赋值给一个变量的,打印变量才能现在值得,不然就是none a = count(5) print(a)
方法的封装:
如果两个不同的py文件在同一个文件夹中,比如tools.py和demo2.py在同一个文件下,tools.py封装了query和commit方法;在demo2.py中调用query和commit方法
只需输入 from tools import query,commit