脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python远程连接服务器MySQL数据库

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

2021-03-12 00:16Eddy_zheng Python

这篇文章主要为大家详细介绍了python远程连接服务器MySQL数据库,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- 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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/eddy_zheng/article/details/53947398

延伸 · 阅读

精彩推荐