本地Python连接服务器中的Mysql数据库

来源:互联网 发布:教师网络研修 编辑:程序博客网 时间:2024/05/31 15:19

1、Python中安装mysql驱动

1.1、Python下安装mysql驱动:

pip installmysql-connector-python --allow-external mysql-connector-python

如果上面的命令安装失败,可以试试另一个驱动:

pip installmysql-connector

1.2、anaconda下安装mysql驱动:

conda installmysql-connector-python

 

2、连接到服务器端的mysql数据库

仅以查询数据库中某一数据表为例,

# 导入MySQL驱动import mysql.connector# 连接mysql,括号内是服务器地址, 端口号, 用户名,密码,存放数据的数据库conn = mysql.connector.connect( host='#', port='#', user='#', password='#', database='#')cursor = conn.cursor(buffered=True) # Locate the Cursor, all that was required was for buffered to be set to true#获得表中有多少条数据sqlcom="select * from china_sites_20140513" # SQL commandaa=cursor.execute(sqlcom) # Execute the commandprint(aa)#查询表中数据,并以每行一个元祖打印rows = cursor.fetchall() #使用 fetchall 函数,将结果集(多维元组)存入 rows 里面#依次遍历结果集,发现每个元素,就是表中的一条记录,用一个元组来显示for a in rows:    print(a)


原创粉丝点击