[本文出自天外归云的博客园]
安装pymysql
首先需要安装pymysql,通过pip安装即可:
pip install pymysql
操作mysql数据库
然后就可以在python代码中操作mysql数据库了,代码如下:
#!/usr/bin/env python # -*- coding: utf8 -*- import pymysql class MySQL(): def __init__(self,host,user,password,db,port): self.db= pymysql.connect(host=host,user=user,password=password,db=db,port=port) self.cur = self.db.cursor() print(self.__class__.__name__+"对象已创建") def query(self,sql): #query try: self.cur.execute(sql) results = self.cur.fetchall() return results except Exception as e: raise e def execute(self,sql): #update,insert,delete try: self.cur.execute(sql) self.db.commit() except Exception as e: self.db.rollback() def __del__(self): self.db.close() print(self.__class__.__name__+"对象已释放") if __name__ == '__main__': host = "" user = "" password = "" db = "" port = xxxx mysql = MySQL(host,user,password,db,port) query_sql = "xxxx" update_sql = "xxxx" results = mysql.query(query_sql) print(results) mysql.execute(update_sql) print("结束")
其中需要填写的MySQL连接信息有:
host:一般是数据库访问的ip地址(需要用引号引上,字符串类型)
user:数据库访问的用户名(需要用引号引上,字符串类型)
password:数据库访问用户的密码(需要用引号引上,字符串类型)
port:数据库访问端口号(不能用引号引,数字类型)
db:数据库名(需要用引号引上,字符串类型)
相关文章: