python远程连接服务器MySQL数据库 python远程连接服务器MySQL数据库

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python远程连接服务器MySQL数据库 python远程连接服务器MySQL数据库

Eddy_zheng   2021-03-31 我要评论

这里默认大家都已经配置安装好 MySQL 和 Python 的MySQL 模块,且默认大家的DB内表和访问账号权限均已设置无误,下面直接代码演示:

# -*- coding: utf-8 -*-
"""
Created on Fri Dec 30 10:43:35 2016

@author: zhengyongzhe
"""

import MySQLdb
import cPickle as pk


def write2file(DB_data,save_filename):
  """数据写入本地"""
  with open(save_filename, 'w') as f:
    pk.dump(DB_data, f))

# 创建数据库连接
conn2db = MySQLdb.connect(
      host='111.111.111.111',# host
      port = 3306, # 默认端口,根据实际修改
      user='username',# 用户名
      passwd='passwd', # 密码
      db ='DBname', # DB name
      )

cur = conn2db.cursor() # 操作游标
DB_data = cur.execute("select * from table_name;") # SQL语句 ,查询需要到处内容

# 获取多条数据
DB_datas = cur.fetchmany(DB_data) 
# 写入本地
write2file(DB_datas,'save_table_name')

"""
# 打印表中数据,chek data
for info in DB_datas:
  print info
"""
cur.close() 
conn2db.commit()

try:
  conn2db.close() # 关闭连接
  print "closed connection..."
except Exception,e:
  print Exception,":",e

以上代码演示Python远程连接服务器MySQL数据库,工程中还需要考虑可能出现的bug。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们