介绍
介绍
今天我们学习如何通过Python操作MySQL数据库。
在Python2.7下使用的是pymysql这个软件包,跟着福哥来操作吧。
安装
安装pymysql
直接使用pip安装即可
pip insall pymysql
![139909e86a2399ab40891cb83413b1c7.png](https://i-blog.csdnimg.cn/blog_migrate/12b79cfc781b339428abfb82aa5bbde4.jpeg)
授权
MySQL数据库服务器默认只能在安装了数据库服务器的本机操作,也就是在TFLinux上操作,但是我们的python是安装在TFWindows上的啊!所以,我们要授权任何电脑都可以操作TFLinux上的MySQL数据库。当然了,肯定是需要正确的用户名和密码的啦!
在TFLinux上登录mysql
[root@tfdev ~]# mysql -uroot -pabcdefmysql: [Warning] Using a password on the command line interface can be insecure.Welcome to the MySQL monitor. Commands end with ; or g.Your MySQL connection id is 3Server version: 5.7.28 MySQL Community Server (GPL)Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.mysql>
授权tfse用户可以在任意电脑上连接MySQL数据库服务器,且对数据库tfse有完全控制权限
mysql> grant all on tfse.* to tfse@'%' identified by 'abcdef';Query OK, 0 rows affected, 1 warning (0.02 sec)
测试
建立MySQLDemo.py用来进行pymysql的测试
测试连接
写入如下代码,测试mysql的连接
import pymysqlcn = pymysql.connect("192.168.1.168","tfse","abcdef")
如果没有报错,证明连接成功了!
测试写入数据
写入如下代码,向websites表写入一条数据
import pymysqltry: # connection cn = pymysql.connect("192.168.1.168","tfse","abcdef") cursor = cn.cursor() # select database cn.select_db('tfse')except Exception as e: print e exit()try: # ins