- 在服务端(centos7)安装mysql的方法在我很早之前博客 https://blog.youkuaiyun.com/weixin_42744102/article/details/86676124 里面就已经详细说明了。
- 按照上面的步骤安装完成后,以终端输入mysql可以进入mysql monitor为成功标志。
- 这时候,我们需要远程连接这个mysql服务器,服务端口默认为3306,很多人反应本地的机器连不上mysql服务端,很多是因为云服务器供应商禁止了这个端口的入度,需要配置一下安全组,具体的在 https://blog.youkuaiyun.com/weixin_42744102/article/details/86769753 中详细讲解了。
- 之后,假如还连不上,且报错类似 **1130, u"Host XXX is not allowed to connect to this MySQL server"**那就意味着mysql数据库没有配置给所有的公网ip登录。这时候,很简单,执行以下的命令:
>>>use mysql
>>>update user set host = '%' where user = 'root';
这时候可能会报一个错 not allowed to connect to this MySQL ERROR 1062 (23000): Duplicate entry ‘%-root’ for key ‘PRIMARY’,忽略它即可,然后继续:
>>>flush privileges;
不出意外的话,在使用远程连接,就可以连接了。
- 使用pymysql连接远程mysql,如果直连,则直接
import pymysql
conn = pymysql.connect("<your host>","<your username>","<your passowrd>","mysql")
c = conn.cursor()
c.execute("""select * from user where user='root';""")
res = c.fetchall()
print(res)
用这个方法可以查询mysql这个数据库里面user表的所有user字段名为root的记录,并以元组的形式返回打印出来。