菁英科技(卓目鸟学苑)- 专注软件测试菁英教育

标题: MySQL设置IP连接和Python操作数据库 [打印本页]

作者: chelang    时间: 2020-2-22 15:20
标题: MySQL设置IP连接和Python操作数据库
许多同学在学习数据库的时候不知如何设置才能让自己PC上的MySQL让别人可以访问以及如何去利用Python操作数据库,今天就送点干货给大家。

一、先看看怎么设置ip连接数据库

默认情况下mysql只允许本地进入设置,如果需要外部IP连接到mysql,需要向mysql数据库里的“user”表里添加相关授权。
进入命令行界面(Window+r、输入cmdenter进入):

1. mysql -uroot -p密码    #登录mysql
2. use mysql;             #使用mysql数据库
3. grant all privileges on *.* to root@'%'  identified by '密码' WITH GRANT OPTION;    #授予权限
4. flush privileges;         #刷新权限使其生效

操作完后才能后我们自己PC上的MySQL就可以ip访问了。

二、Python操作数据库

1. 连接数据库查询数据

#查询操作。
import pymysql
mysql_connect = pymysql.connect(host='localhost',
user='root', passwd='',
db='niushop_b2c',
port=3306,
charset='utf8')
#创建游标并读取数据库数据,逐行读取 mysql_cursor = mysql_connect.cursor()
#执行查询语句
mysql_cursor.execute('select * fromns_member;')
data = mysql_cursor.fetchall()
print(data)
mysql_connect.close()
mysql_cursor.close()

2. 修改数据

#修改表数据。
import pymysql
mysql_connect =pymysql.connect(host='localhost',
user='root',
passwd='123456', db='test',
port=3307, charset='utf8')
#创建游标并读取数据库数据,逐行读取
mysql_cursor = mysql_connect.cursor()
#执行修改表的语句
mysql_cursor.execute('update pay setmax="6000" where dengji=1;')
#提交操作
mysql_connect.commit()
mysql_connect.close()
mysql_cursor.close()






欢迎光临 菁英科技(卓目鸟学苑)- 专注软件测试菁英教育 (http://www.zmnxy.com/) Powered by Discuz! X3.4