python3---连接本地与远程机器的mysql数据库,在特定数据表中增加数据、查询数据

python3—连接本地与远程机器的mysql数据库,在特定数据表中增加数据、查询数据

-------------------------------------本地的mysql数据库--------------------------------------
1、python3连接mysql出现如下错误:
root@kali:~/pywork# python3 conn_mysql_test.py 
(1698, "Access denied for user 'root'@'localhost'")
Traceback (most recent call last):
  File "conn_mysql_test.py", line 23, in <module>
    db = connect_mysql()
  File "conn_mysql_test.py", line 19, in connect_mysql
    return cms
UnboundLocalError: local variable 'cms' referenced before assignment
root@kali:~/pywork#
问题解决方式如下:
参考:https://blog.csdn.net/junli_chen/article/details/51220179

进入本机的mysql数据库中:
root@kali:/etc/mysql# mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 33
Server version: 10.1.26-MariaDB-1 Debian buildd-unstable

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases
    -> ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| python3db          |
+--------------------+
4 rows in set (0.01 sec)

MariaDB [(none)]> grant all privileges on *.* to 'root'@'localhost' identified by 'root' with grant option;
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    33
Current database: *** NONE ***

Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]>
2、本机数据库数据情况:
root@kali:/etc/mysql# mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 33
Server version: 10.1.26-MariaDB-1 Debian buildd-unstable

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS python3db DEFAULT CHARSET utf8;#创建数据库python3db
Query OK, 1 row affected (0.01 sec)
MariaDB [(none)]> show databases
    -> ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| python3db          |
+--------------------+
4 rows in set (0.01 sec)
ariaDB [(none)]> use python3db
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [python3db]> CREATE TABLE user (name VARCHAR(20), sex CHAR(1), birth DATE, birthaddr VARCHAR(20));#创建user数据表
Query OK, 0 rows affected (0.07 sec)

MariaDB [python3db]>
MariaDB [python3db]> show tables;
+---------------------+
| Tables_in_python3db |
+---------------------+
| user                |
+---------------------+
1 row in set (0.00 sec)

MariaDB [python3db]>
MariaDB [python3db]> select * from user;
+---------+------+------------+-----------+
| name    | sex  | birth      | birthaddr |
+---------+------+------------+-----------+
| python3 | f    | 2017-06-21 | shenzhen  |
| python3 | m    | 2018-05-01 | hangzhou  |
| lilei   | m    | 2018-05-01 | hangzhou  |
| mayun   | m    | 2019-05-01 | guagzhou  |
| mayun   | f    | 2019-05-23 | dayuan    |
+---------+------+------------+-----------+
5 rows in set (0.00 sec)

MariaDB [python3db]>
3、使用python3语句在user数据表中增加数据,并查询user数据表的所有数据

Python源码:
root@kali:~/pywork# cat conn_mysql_test.py
#!/usr/bin/python3.6
# --*-- coding:utf-8 --*--

import pymysql

def connect_mysql():
    db_config = {
        'host':'127.0.0.1',#本机数据库地址
        'port':3306,
        'user':'root',
        'password':'root',
        'db':'python3db',#需要连接的数据库
        'charset':'utf8mb4'#编码
    }
    try:
        cms = pymysql.connect(**db_config)
        cur = cms.cursor()#获取一个游标
        cur.execute("insert into user values('xuweiwei','m','2008-05-21','nanchangshi');")#在user数据表插入一条数据
        cur.execute('flush privileges;')#必须实时更新数据
        cur.execute('select * from user;')#查询USER数据表中所有数据
        data = cur.fetchall()
        for d in data:#打印查询的数据
                print('name: '+str(d[0])+'\t'+'sex: '+str(d[1])+'\t'+'birth: '+str(d[2])+'\t'+'birthaddr: '+str(d[3]))
        cur.close()
    except Exception as e:
        print(e)

db = connect_mysql()
#print(dir(db))
#print(type(db))

root@kali:~/pywork# 
4、脚本运行后情况如下:
root@kali:~/pywork# python3 conn_mysql_test.py 
name: python3   sex: f  birth: 2017-06-21   birthaddr: shenzhen
name: python3   sex: m  birth: 2018-05-01   birthaddr: hangzhou
name: lilei sex: m  birth: 2018-05-01   birthaddr: hangzhou
name: mayun sex: m  birth: 2019-05-01   birthaddr: guagzhou
name: mayun sex: f  birth: 2019-05-23   birthaddr: dayuan
name: xuweiwei  sex: m  birth: 2008-05-21   birthaddr: nanchangshi
root@kali:~/pywork# 
5、再到本机的mysql查询到数据如下:
MariaDB [python3db]> 
MariaDB [python3db]> select * from user;
+----------+------+------------+-------------+
| name     | sex  | birth      | birthaddr   |
+----------+------+------------+-------------+
| python3  | f    | 2017-06-21 | shenzhen    |
| python3  | m    | 2018-05-01 | hangzhou    |
| lilei    | m    | 2018-05-01 | hangzhou    |
| mayun    | m    | 2019-05-01 | guagzhou    |
| mayun    | f    | 2019-05-23 | dayuan      |
| xuweiwei | m    | 2008-05-21 | nanchangshi |
+----------+------+------------+-------------+
6 rows in set (0.00 sec)

MariaDB [python3db]> 
*************************远程windows server 2003的mysql数据库***************
6、连接远程的windows server 2003服务器的数据库读取数据

python源码:

root@kali:~/pywork# cat conn_mysql_remote.py 
#!/usr/bin/python3.6
# --*-- coding:utf-8 --*--

import pymysql

def connect_mysql():
    db_config = {
        'host':'192.168.40.239',#远程windows server 2003数据库地址
        'port':3306,
        'user':'root',
        'password':'root',
        'db':'test',#需要连接的数据库test
        'charset':'utf8mb4'#编码
    }
    try:
        cms = pymysql.connect(**db_config)
        cur = cms.cursor()#获取一个游标
        cur.execute("insert into member values('12','python','1234567890');")#在member数据表插入一条数据
        cur.execute('flush privileges;')#必须实时更新数据
        cur.execute('select * from member;')#查询member数据表中所有数据
        data = cur.fetchall()
        for d in data:#打印查询的member数据表的数据
                print('User ID: '+str(d[0])+'\t'+'user: '+str(d[1])+'\t'+'password: '+str(d[2]))
        cur.close()
    except Exception as e:
        print(e)

db = connect_mysql()
#print(dir(db))
#print(type(db))

root@kali:~/pywork# 
7、python脚本第一次运行会出现如下报错信息(没有权限):
root@kali:~/pywork# python3.6 conn_mysql_remote.py 
(1130, "Host '192.168.40.240' is not allowed to connect to this MySQL server")
root@kali:~/pywork#

解决办法为:
在windows server 2003服务器的数据库中修改以下内容:
参考:https://www.cnblogs.com/Bighua/p/7629082.html

查看user表中的数据:select Host, User,Password from user;
修改user表中的Host:update user set Host='%' where User='root';
最后刷新一下:flush privileges;
8、连接远程服务器的数据库情况如下:
root@kali:~/pywork# vi conn_mysql_remote.py 
root@kali:~/pywork# python3.6 conn_mysql_remote.py 
User ID: 7  user: lifeifei  password: 2556336555355
User ID: 2  user: daxuexe   password: 12345678ee
User ID: 10 user: wumingjun password: 368228687741
User ID: 3  user: xuweibo   password: 145263
User ID: 4  user: wumingjun password: 185256696889
User ID: 5  user: xiedidi   password: 147258663555
User ID: 6  user: lilei password: 2341234124512
User ID: 1  user: hangguo   password: 1221412r34
User ID: 9  user: damaomao  password: 345325fwewr325
User ID: 8  user: maoxuxu   password: 34324523ffw3e4
User ID: 11 user: python    password: 1234567890
User ID: 12 user: python    password: 1234567890
root@kali:~/pywork# 

猜你喜欢

转载自blog.csdn.net/xwbk12/article/details/80774892
今日推荐