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

yipeiwu_com6年前服务器

本文实例为大家分享了python远程连接服务器MySQL数据库的具体代码,供大家参考,具体内容如下

这里默认大家都已经配置安装好 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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3 jupyter notebook 服务器搭建过程

1. jupyter notebook 安装 •创建 jupyter 目录 mkdir jupyter cd jupyter/ •创建独立的 Python3...

python和shell监控linux服务器的详细代码

本文实例为大家分享了python和shell监控linux服务器的具体代码,供大家参考,具体内容如下 1、 shell监控负载 监控原理:使用uptime来获取负载的信息,然后通过字符...

python 从远程服务器下载东西的代码

复制代码 代码如下:# _*_ coding:utf-8 _*_# name gefile.pyimport osimport statimport socketimport param...

PHP实现检测客户端是否使用代理服务器及其匿名级别

要判断客户端是否使用代理服务器,可以从客户端所发送的环境变量信息来判断。 具体来说,就是看HTTP_VIA字段,如果这个字段设置了,说明客户端使用了代理服务器。 匿名级别可以参考下表来判...

在windows服务器开启php的gd库phpinfo中未发现

在windows服务器开启php的gd库时,使用cgi之后phpinfo()得到的结果中 Configure Command 中并没有出现gd. Configure Command 后显...