mysql 与 python 交互

  • from pymysql import connect  #导入pymysql包
  • class MysqlHttp:
    • def __init__(self,host,port,user,password,db,charset):  #host:sql服务器所在的机器ip,mysql端口为3306,登录mysql的用户名及密码,db:数据库名charset:编码  utf8
      • self.host=host
      • self.port=port
      • self.user=user
      • self.password=password
      • self.db=db
      • self.charset=charset
    • def open(self):
      • #创建链接对象
      • self.conn=connect(host=self.host,port=self.port,user=self.user,password=self.password,db=self.db,charset=self.charset)
      • #创建游标对象
      • self.cur=self.conn.cursor()
    • def close(self):
      • #关闭游标对象
      • self.cur.close()
      • #关闭链接
      • self.conn.close()
    • def cud(self,sql,params=[]): #增删改
      • self.open()   #开启链接
      • self.cur.execute(sql,params)  #执行sql语句,返回受影响的行数 params,sql语句参数化,防止sql注入攻击,是一个列表
      • self.conn.commit()        #执行增删改操作,需要提交
      • self.close()   #关闭链接
    • def get_one(self,sql,params=[]): #查第一行
      • self.open()
      • self.cur.execute(sql,params)
      • result=self.cur.fetchone()  #获取查询结果的第一行数据,是一个元组,查不到返回None
      • #result=self.cur.fetchone()  #获取查询结果的第二行数据,
      • #result=self.cur.fetchall()  #获取剩下的所有结果
      • self.close()
      • return result
    • def get_all(self,sql,params=[]): #查所有
      • self.open()
      • self.cur.execute(sql,params)
      • result=self.cur.fetchall() #获取所有的查询结果,每一行数据是一个元组,所有行在组成一个元组,查不到返回一个空元祖
      • self.close()
      • return result
  • def main():
    • http=MysqlHttp("192.168.28.132",3306,"root","root","test","utf8")
    • sql="desc students"
    • print(http.get_all(sql))
    • sql="insert into students(name) values(%s)"  #sql语句参数化,防止恶意sql语句注入攻击
    • params=["李振斌"]
    • http.cud(sql,params)
    • sql="select * from students"
    • print(http.get_all(sql))
    • sql="select count(*) from students group by birthday"
    • print(http.get_all(sql))
    • sql="select * from students where name=%s"
    • params=["李振斌"]
    • print(http.get_all(sql,params))
  • if __name__ == '__main__':
    • main()

猜你喜欢

转载自blog.csdn.net/qq_41654985/article/details/80542835