Python3操作MySQL数据库

来源:互联网 发布:怎样成为数据分析师 编辑:程序博客网 时间:2024/06/05 11:09


1. 使用PyMySQL连接MySQL数据库


1.1 准备工作

1. 安装PyMySQL,使用pip安装即可
    pip install PyMySQL
2. MySQL数据准备(过程略,结果如下图)
   

1.2 查询下一条结果

代码示例:
import pymysql# 打开连接conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='star', charset='utf8')# 创建游标cursor = conn.cursor()# 执行SQLsql = 'select * from star'cursor.execute(sql)# 获取全部数据data = cursor.fetchone()print('当前数据: ', data)data_1 = cursor.fetchone()print('下一条数据: ', data_1)# 关闭数据库连接conn.close()
执行结果:
当前数据:  (1, '杨幂', datetime.date(1984, 6, 1))
下一条数据:  (2, '李小璐', datetime.date(1989, 5, 1))

1.3 查询全部结果

代码示例:
import pymysql# 打开连接conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='star', charset='utf8')# 创建游标cursor = conn.cursor()# 执行SQLsql = 'select * from star'cursor.execute(sql)# 获取全部数据data = cursor.fetchall()print('全部数据: ', data)print('第一条数据: ', data[0])# 按行打印查询结果(可选字段)for row in data:    print(row[1], row[2])# 关闭数据库连接conn.close()
执行结果:
全部数据:  ((1, '杨幂', datetime.date(1984, 6, 1)), (2, '李小璐', datetime.date(1989, 5, 1)), (3, '赵奕欢', datetime.date(1990, 10, 10)), (4, '谭松韵', datetime.date(1993, 7, 1)), (5, '孙允珠', datetime.date(2001, 3, 8)))
第一条数据:  (1, '杨幂', datetime.date(1984, 6, 1))
杨幂 1984-06-01
李小璐 1989-05-01
赵奕欢 1990-10-10
谭松韵 1993-07-01
孙允珠 2001-03-08

1.4 参考资料

https://github.com/PyMySQL/PyMySQL
http://www.runoob.com/python3/python3-mysql.html

2. 使用Paramiko远程连接服务器并执行MySQL命令


2.1 准备工作

1. 安装Paramiko,使用pip安装即可
pip install paramiko
2.数据准备(略)

2.2 示例代码

注:使用时替换代码中的各地址、端口、账号、密码、数据库及SQL即可
import paramiko# 打开连接ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器, 需要服务器地址, 端口, 登录用户, 登录密码ssh.connect('123.45.67.89', 12345, 'root', '123456')# 连接数据库并执行SQL, 需要数据库地址, 数据库账号及密码, 查询SQLdatabase = 'user'sql = 'SELECT id, name, mobile FROM fy_agent WHERE mobile IN (13012345678, 13212345678)'sql1 = 'mysql -h %s -u %s -p%s -D%s -e "%s"' % ('abc.mysql.rds.aliyuncs.com', 'root', '123456', database, sql)stdin, stdout, stderr = ssh.exec_command(sql1)# 打印结果result = stdout.readlines()print(result)data_1 = result[1]print(data_1)                # 查询结果默认带表头, 结果数据从下一条记录开始;print(data_1.replace('\t', '').replace('\n', ''))    # 将结果中的\t\n替换掉# 关闭连接ssh.close()
执行结果:
['id\tname\tmobile\n', '13480\t红包昆明二\t13212345678\n', '13488\t广东\t13012345678\n']
13480 红包昆明二 13212345678

13480红包昆明二13212345678

2.3 参考资料

http://www.paramiko.org/
http://blog.csdn.net/songfreeman/article/details/50920767



原创粉丝点击