千家信息网

python如何使用mysql-connector方式连接mysql数据库

发表于:2024-12-05 作者:千家信息网编辑
千家信息网最后更新 2024年12月05日,python如何使用mysql-connector方式连接mysql数据库?一起跟小编来看看吧。用linux上 用python对mysql进行连接前提遇到的问题记录:在linux上安装 (base)
千家信息网最后更新 2024年12月05日python如何使用mysql-connector方式连接mysql数据库

python如何使用mysql-connector方式连接mysql数据库?一起跟小编来看看吧。

用linux上 用python对mysql进行连接前提遇到的问题记录:在linux上安装 (base) [sqoop@flink-slave5 bin]$ ./pip install mysql                  Looking in indexes: http://pypi.douban.com/simpleCollecting mysql  Downloading http://pypi.doubanio.com/packages/bf/5f/b574ac9f70811df0540e403309f349a8b9fa1a25d3653824c32e52cc1f28/mysql-0.0.2.tar.gz (1.9 kB)Collecting mysqlclient  Downloading http://pypi.doubanio.com/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz (85 kB)     |████████████████████████████████| 85 kB 4.0 MB/s     ERROR: Command errored out with exit status 1:     command: /data/python_test/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s6ioj0n3/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s6ioj0n3/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-s6ioj0n3/mysqlclient/pip-egg-info         cwd: /tmp/pip-install-s6ioj0n3/mysqlclient/    Complete output (12 lines):    /bin/sh: mysql_config: command not found    /bin/sh: mariadb_config: command not found    /bin/sh: mysql_config: command not found    Traceback (most recent call last):      File "", line 1, in       File "/tmp/pip-install-s6ioj0n3/mysqlclient/setup.py", line 16, in         metadata, options = get_config()      File "/tmp/pip-install-s6ioj0n3/mysqlclient/setup_posix.py", line 61, in get_config        libs = mysql_config("libs")      File "/tmp/pip-install-s6ioj0n3/mysqlclient/setup_posix.py", line 29, in mysql_config        raise EnvironmentError("%s not found" % (_mysql_config_path,))    OSError: mysql_config not found    ----------------------------------------ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.解决方法: [root@flink-slave5 ~]# yum install mysql-devel gcc gcc-devel python-devel 参考链接 https://www.jianshu.com/p/5b6deb15bd21 (base) [sqoop@flink-slave5 bin]$ pwd/data/python_test/bin(base) [sqoop@flink-slave5 bin]$ ./pip install mysqlLooking in indexes: http://pypi.douban.com/simpleCollecting mysql  Downloading http://pypi.doubanio.com/packages/bf/5f/b574ac9f70811df0540e403309f349a8b9fa1a25d3653824c32e52cc1f28/mysql-0.0.2.tar.gz (1.9 kB)Collecting mysqlclient  Downloading http://pypi.doubanio.com/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz (85 kB)     |████████████████████████████████| 85 kB 14.8 MB/s Building wheels for collected packages: mysql, mysqlclient  Building wheel for mysql (setup.py) ... done  Created wheel for mysql: filename=mysql-0.0.2-py3-none-any.whl size=1243 sha256=81bb94d982e366e617bf2dd96df9735009fea2ad983b60198d054773df25dde2  Stored in directory: /home/sqoop/.cache/pip/wheels/42/09/8b/d90224fd8b5636800fa21b9ede51f208bb1781bf7f52b89085  Building wheel for mysqlclient (setup.py) ... done  Created wheel for mysqlclient: filename=mysqlclient-1.4.6-cp37-cp37m-linux_x86_64.whl size=59120 sha256=1d83233315a664a264e51acb1b0288979b0f621da6c15a0fc3688e5f1c09fda4  Stored in directory: /home/sqoop/.cache/pip/wheels/f9/8e/98/19b6ee3ca946f2f107a41bc88a15c3844d406ceeae32446784Successfully built mysql mysqlclientInstalling collected packages: mysqlclient, mysqlSuccessfully installed mysql-0.0.2 mysqlclient-1.4.6然后执行: (base) [sqoop@flink-slave5 bin]$ ./pip install mysql-connector .........在linux环境上测试成功 (base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql.py MySQL版本: 8.0.13 (base) [sqoop@flink-slave5 majihui_test]$ pwd/data/majihui_test(base) [sqoop@flink-slave5 majihui_test]$ cat python_connect_mysql.py # -*- coding: UTF-8 -*-import mysql.connector# 打开数据库连接db = mysql.connector.connect(       host="10.9.36.253",       user="rpt",       passwd="Rpt1234!", # 写上你的数据库密码       database='rpt',       auth_plugin='mysql_native_password')# 获取操作游标cursor = db.cursor()# 执行SQL语句cursor.execute("SELECT VERSION()")# 获取一条数据data = cursor.fetchone()print("MySQL版本: %s " % data)# 关闭游标&数据库连接cursor.close()db.close()(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql.py MySQL版本: 8.0.13 第三:  对数据表进行增删改查    1、首先我们给student的表增加一个学生用户:        mysql> select * from student ;            +-----------+--------+------+------+-------+            | Sno       | Sname  | Ssex | Sage | Sdept |            +-----------+--------+------+------+-------+            | 100215122 | 刘晨   | 女   |   19 | CS    |            | 100215123 | 王敏   | 女   |   18 | MA    |            | 200215121 | 李勇   | 女   |   20 | CS    |            +-----------+--------+------+------+-------+            3 rows in set (0.00 sec)# 插入学生代码sql = "INSERT INTO student (Sno, Sname, Ssex,Sage,Sdept) VALUES (%s, %s, %s, %s, %s)"val = (200215122, "马吉辉", "男", 27, CS)cursor.execute(sql, val)db.commit()print(cursor.rowcount, "记录插入成功。")完整代码如下:  执行了2次,插入了2次数据 (base) [sqoop@flink-slave5 majihui_test]$ cat python_connect_mysql_insert.py                             # -*- coding: UTF-8 -*-import mysql.connector# 打开数据库连接db = mysql.connector.connect(       host="10.9.36.253",       user="rpt",       passwd="Rpt1234!", # 写上你的数据库密码       database='rpt',       auth_plugin='mysql_native_password')# 获取操作游标cursor = db.cursor()# 插入学生代码sql = "INSERT INTO student (Sno, Sname, Ssex,Sage,Sdept) VALUES (%s, %s, %s, %s, %s)"val = (200215123, "王金灿", "男", 30, "CS")# 执行SQL语句cursor.execute(sql, val)# 提交sql语句对事务进行提交db.commit()# 打印结果 # 使用cursor.rowcount,返回查询结果集中的行数。如果没有查询到数据或者还没有查询,则结果为 -1,否则会返回查询得到的数据行数;print(cursor.rowcount, "记录插入成功。")# 关闭游标&数据库连接cursor.close()db.close()(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_insert.py 1 记录插入成功。mysql> select * from student ;+-----------+-----------+------+------+-------+| Sno       | Sname     | Ssex | Sage | Sdept |+-----------+-----------+------+------+-------+| 100215122 | 刘晨      | 女   |   19 | CS    || 100215123 | 王敏      | 女   |   18 | MA    || 200215121 | 李勇      | 女   |   20 | CS    || 200215122 | 马吉辉    | 男   |   27 | CS    || 200215123 | 王金灿    | 男   |   30 | CS    |+-----------+-----------+------+------+-------+5 rows in set (0.00 sec)代码解释:        我们使用 cursor.execute 来执行相应的 SQL 语句,        val 为 SQL 语句中的参数,SQL 执行后使用 db.commit() 进行提交。        需要说明的是,我们在使用 SQL 语句的时候,可以向 SQL 语句传递参数,        这时 SQL 语句里要统一用(%s)进行占位,否则就会报错。        不论插入的数值为整数类型,还是浮点类型,都需要统一用(%s)进行占位。        另外在用游标进行 SQL 操作之后,还需要使用 db.commit() 进行提交,否则数据不会被插入。小结:    上面这段代码中有两个重要的对象你需要了解下,分别是 Connection 和 Cursor。        Connection 就是对数据库的当前连接进行管理,我们可以通过它来进行以下操作:        1、通过指定 host、user、passwd 和 port 等参数来创建数据库连接,这些参数分别对应着数据库 IP 地址、用户名、密码和端口号;        2、使用 db.close() 关闭数据库连接;        3、使用 db.cursor() 创建游标,操作数据库中的数据;        4、使用 db.begin() 开启事务;        5、使用 db.commit() 和 db.rollback(),对事务进行提交以及回滚。    当我们通过cursor = db.cursor()创建游标后,就可以通过面向过程的编程方式对数据库中的数据进行操作:        1、使用cursor.execute(query_sql),执行数据库查询;        2、使用cursor.fetchone(),读取数据集中的一条数据;        3、使用cursor.fetchall(),取出数据集中的所有行,返回一个元组 tuples 类型;        4、使用cursor.fetchmany(n),取出数据集中的多条数据,同样返回一个元组 tuples;        5、使用cursor.rowcount,返回查询结果集中的行数。如果没有查询到数据或者还没有查询,则结果为 -1,否则会返回查询得到的数据行数;        6、使用cursor.close(),关闭游标。 2、# 查询年龄大于20的sql = 'SELECT * FROM student WHERE Sage>=20'cursor.execute(sql)data = cursor.fetchall()for each_player in data:  print(each_player)完整代码如下:(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_select.py ('200215121', '李勇', '女', 20, 'CS')('200215122', '马吉辉', '男', 27, 'CS')('200215123', '王金灿', '男', 30, 'CS')(base) [sqoop@flink-slave5 majihui_test]$ cat python_connect_mysql_select.py                             # -*- coding: UTF-8 -*-import mysql.connector# 打开数据库连接db = mysql.connector.connect(       host="10.9.36.253",       user="rpt",       passwd="Rpt1234!", # 写上你的数据库密码       database='rpt',       auth_plugin='mysql_native_password')# 获取操作游标cursor = db.cursor()# 查询年龄大于20的sql = 'SELECT * FROM student WHERE Sage>=20'cursor.execute(sql)data = cursor.fetchall()for each_student in data:  print(each_student)# 关闭游标&数据库连接cursor.close()db.close()(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_select.py                          ('200215121', '李勇', '女', 20, 'CS')('200215122', '马吉辉', '男', 27, 'CS')('200215123', '王金灿', '男', 30, 'CS')----3、如何修改数据呢?# 修改马吉辉的CS 修改成SS sql = 'UPDATE student SET Sdept = %s WHERE Sname = %s'val = ("SS", "马吉辉")cursor.execute(sql, val)db.commit()print(cursor.rowcount, "记录被修改。")完整代码如下:(base) [sqoop@flink-slave5 majihui_test]$ cat python_connect_mysql_update.py                             # -*- coding: UTF-8 -*-import mysql.connector# 打开数据库连接db = mysql.connector.connect(       host="10.9.36.253",       user="rpt",       passwd="Rpt1234!", # 写上你的数据库密码       database='rpt',       auth_plugin='mysql_native_password')# 获取操作游标cursor = db.cursor()sql = 'UPDATE student SET Sdept = %s WHERE Sname = %s'val = ("SS", "马吉辉")cursor.execute(sql, val)db.commit()print(cursor.rowcount, "记录被修改。")# 关闭游标&数据库连接cursor.close()db.close()(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_update.py    1 记录被修改。mysql> select * from student where Sname = "马吉辉";+-----------+-----------+------+------+-------+| Sno       | Sname     | Ssex | Sage | Sdept |+-----------+-----------+------+------+-------+| 200215122 | 马吉辉    | 男   |   27 | SS    |+-----------+-----------+------+------+-------+1 row in set (0.00 sec)---------4、最后我们看下如何删除王金灿这个同学的数据:# 删除王金灿这个同学的数据sql = 'DELETE FROM student WHERE Sname = %s'val = ("王金灿",)cursor.execute(sql, val)db.commit()print(cursor.rowcount, "记录删除成功。")完整代码如下:(base) [sqoop@flink-slave5 majihui_test]$ cat python_connect_mysql_delete.py                             # -*- coding: UTF-8 -*-import mysql.connector# 打开数据库连接db = mysql.connector.connect(       host="10.9.36.253",       user="rpt",       passwd="Rpt1234!", # 写上你的数据库密码       database='rpt',       auth_plugin='mysql_native_password')# 获取操作游标cursor = db.cursor()# 删除王金灿这个同学的数据sql = 'DELETE FROM student WHERE Sname = %s'val = ("王金灿",)cursor.execute(sql, val)db.commit()print(cursor.rowcount, "记录删除成功。")# 关闭游标&数据库连接cursor.close()db.close()(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_delete.py    1 记录删除成功。mysql> select * from student ;+-----------+-----------+------+------+-------+| Sno       | Sname     | Ssex | Sage | Sdept |+-----------+-----------+------+------+-------+| 100215122 | 刘晨      | 女   |   19 | CS    || 100215123 | 王敏      | 女   |   18 | MA    || 200215121 | 李勇      | 女   |   20 | CS    || 200215122 | 马吉辉    | 男   |   27 | SS    |+-----------+-----------+------+------+-------+4 rows in set (0.00 sec)第四:    针对上面的操作过程,你可以模拟下数据的 CRUD 操作,但有几点你需要注意。    1. 打开数据库连接以后,如果不再使用,则需要关闭数据库连接,以免造成资源浪费。    2. 在对数据进行增加、删除和修改的时候,可能会出现异常,这时就需要用try...except捕获异常信息。    3、比如针对插入同学王金灿这个操作,你可以写成下面这样:第五:      加入python异常完整代码如下:(base) [sqoop@flink-slave5 majihui_test]$ cat python_connect_mysql_insert_traceback.py                         # -*- coding: UTF-8 -*-import mysql.connectorimport traceback# 打开数据库连接db = mysql.connector.connect(       host="10.9.36.253",       user="rpt",       passwd="Rpt1234!", # 写上你的数据库密码       database='rpt',       auth_plugin='mysql_native_password')# 获取操作游标cursor = db.cursor()# 插入学生代码try:    sql = "INSERT INTO student (Sno, Sname, Ssex,Sage,Sdept) VALUES (%s, %s, %s, %s, %s)"    val = (200215123, "王金灿", "男", 30, "CS")    # 执行SQL语句    cursor.execute(sql, val)    # 提交sql语句对事务进行提交    db.commit()    # 打印结果     # 使用cursor.rowcount,返回查询结果集中的行数。如果没有查询到数据或者还没有查询,则结果为 -1,否则会返回查询得到的数据行数;    print(cursor.rowcount, "记录插入成功。")except Exception as e:    # 打印异常信息    traceback.print_exc()    # 回滚      db.rollback()finally:    # 关闭游标&数据库连接    cursor.close()    db.close()(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_insert_traceback.py1 记录插入成功。mysql> select * from student ;+-----------+-----------+------+------+-------+| Sno       | Sname     | Ssex | Sage | Sdept |+-----------+-----------+------+------+-------+| 100215122 | 刘晨      | 女   |   19 | CS    || 100215123 | 王敏      | 女   |   18 | MA    || 200215121 | 李勇      | 女   |   20 | CS    || 200215122 | 马吉辉    | 男   |   27 | SS    || 200215123 | 王金灿    | 男   |   30 | CS    |+-----------+-----------+------+------+-------+5 rows in set (0.00 sec)再执行一次,就会报错:(base) [sqoop@flink-slave5 majihui_test]$ /data/python_test/bin/python python_connect_mysql_insert_traceback.pyTraceback (most recent call last):  File "python_connect_mysql_insert_traceback.py", line 20, in     cursor.execute(sql, val)  File "/data/python_test/lib/python3.7/site-packages/mysql/connector/cursor.py", line 551, in execute    self._handle_result(self._connection.cmd_query(stmt))  File "/data/python_test/lib/python3.7/site-packages/mysql/connector/connection.py", line 490, in cmd_query    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))  File "/data/python_test/lib/python3.7/site-packages/mysql/connector/connection.py", line 395, in _handle_result    raise errors.get_exception(packet)mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '200215123' for key 'PRIMARY'第八:    我们在python代码中写了 mysql的账号和密码如何 # 建议吧数据库链接信息写到配置文件里,防止密码泄露。import jsonimport tracebackimport mysql.connector# 读取数据库链接配置文件with open('mysql.json', encoding='utf-8') as con_json:    con_dict = json.load(con_json)# 打开数据库链接db = mysql.connector.connect(    host=con_dict['host'],    user=con_dict['user'],    passwd=con_dict['passwd'],    database=con_dict['database'],    auth_plugin=con_dict['auth_plugin'],)# 获取操作游标cursor = db.cursor()try:    sql = 'SELECT id, name, hp_max FROM heros WHERE hp_max>6000'    cursor.execute(sql)    data = cursor.fetchall()    print(cursor.rowcount, '查询成功。')    for each_hero in data:        print(each_hero)except Exception as e:    # 打印异常信息    traceback.print_exc()finally:    cursor.close()    db.close()# 建议吧数据库链接信息写到配置文件里,防止密码泄露。

0