python 连接mysql ---PyMysql
来源:互联网 发布:linux命令行拷贝文件 编辑:程序博客网 时间:2024/05/22 10:38
python连接mysql的工具
python 连接mysql的工具有很多,mysqldb,oursql等,从安装的便利和使用上选择了pymysql
安装
pip install PyMysql
使用
#!/usr/bin/python3# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8import pymysqldef connectdb(): print('创建数据库连接') db = # 注意指定编码的字符集 否则中文可能是乱码 pymysql.connect(host="10.x.x1.1x9",user="xxxx",passwd="xxx",db="data_analyze",charset="utf8") print('连接成功...') return db ;def query(db): cursor=db.cursor() sql="select * from data_analyze.t_game_id limit 2" try: cursor.execute(sql) results=cursor.fetchall() for line in results: param1=line[0] param2=line[1] print "diyige:%s,dierge:%s" %(param1,param2) except: print "ERROR :unable fetch data"def main(): db=connectdb() query(db)if __name__=='__main__': main()
tip:插入删除 update 使用 cursor.execute(sql) 游标对象执行对应的sql就可
阅读全文