一.安装mysql
首先在服务器上安装mysql,因为我用的是ubuntu,所以使用
apt-get install mysql-server
出现设置root账号密码界面,设置密码即可
二.安装pymysql
在主机上python界面安装pymysql来进行远程连接
pip install pymysql
三.在mysql中创建表方便稍后查询
show databases
create database root_test;
use root_test
create table test (id int primary key auto_increment, name char(18) );
insert into test (name) values ('gp');
select * from test;
四.授予root用户远程访问权限
mysql -uroot -p 输入密码
grant all on *.* to 'root'@'%' identified by 'root'
use mysql
select host, user from user;
update user set host = '%' where user = 'root';
select host, user from user;
exit
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
#往下翻,注释掉这一行,保存退出
# bind-address = 127.0.0.1
service mysql restart
五.将服务器的3306端口打开
mysql中键入
show global variables like 'port';
如图,mysql默认3306端口,所以你还要打开3306端口
六.python中键入
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(
host="服务公网地址",
port = 3306,
user ="root", password ="root",
database ="root_test",
charset ="utf8")
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
# 得到一个可以执行SQL语句并且将结果作为字典返回的游标
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定义要执行的SQL语句
effect_row = cursor.execute("select * from test")
print(cursor.fetchall())
# 执行SQL语句
conn.commit()
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()