2025年pymysql 查询(Pymysql查询返回的结果)

pymysql 查询(Pymysql查询返回的结果)Python 可以通过 pymysql 模块来连接 MySQL 数据库 具体步骤如下 安装 pymysql 模块 可以通过以下命令来安装 pymysql 模块 pip install em pymysql em 连接 MySQL 数据库 可以使用以下代码来连接 MySQL 数据库 import em pymysql em 打开数据库连接

大家好,我是讯享网,很高兴认识大家。

Python可以通过pymysql模块来连接MySQL数据库,具体步骤如下:

  1. 安装pymysql模块

可以通过以下命令来安装pymysql模块:

pip install <em>pymysql</em> 

讯享网
  1. 连接MySQL数据库

可以使用以下代码来连接MySQL数据库:


讯享网

讯享网import <em>pymysql</em> # 打开数据库连接 db = <em>pymysql</em>.connect(&quot;host&quot;, &quot;username&quot;, &quot;password&quot;, &quot;database&quot;) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL <em>查询</em> cursor.execute(&quot;SELECT VERSION()&quot;) # 使用 fetchone() 方法获取单条数据. data = cursor.fetchone() print(&quot;Database version : %s &quot; % data) # 关闭数据库连接 db.close() 

其中,host为MySQL服务器地址,username为MySQL登录用户名,password为MySQL登录密码,database为要连接的数据库名称。以上代码连接成功后,输出数据库版本号。

  1. 执行SQL语句

可以使用execute()方法来执行SQL语句,例如:

import <em>pymysql</em> # 打开数据库连接 db = <em>pymysql</em>.connect(&quot;host&quot;, &quot;username&quot;, &quot;password&quot;, &quot;database&quot;) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 执行SQL语句 sql = &quot;SELECT * FROM books&quot; cursor.execute(sql) # 获取所有数据 results = cursor.fetchall() for row in results: id = row[0] title = row[1] author = row[2] price = row[3] print(&quot;id=%d,title=%s,author=%s,price=%f&quot; % (id, title, author, price)) # 关闭数据库连接 db.close() 

以上代码执行了一个查询语句查询books表中的所有数据,并输出到控制台。

  1. 插入数据

可以使用execute()方法来执行插入数据的SQL语句,例如:

讯享网import <em>pymysql</em> # 打开数据库连接 db = <em>pymysql</em>.connect(&quot;host&quot;, &quot;username&quot;, &quot;password&quot;, &quot;database&quot;) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 插入数据 sql = &quot;INSERT INTO books (title, author, price) VALUES (&#39;<em>Python</em>编程&#39;, &#39;张三&#39;, 29.99)&quot; cursor.execute(sql) # 提交事务 db.commit() # 关闭数据库连接 db.close() 

以上代码向books表中插入了一条数据,提交事务后关闭数据库连接。

以上是使用Python连接MySQL数据库的简单示例,可以根据实际需求进行修改和扩展。


小讯
上一篇 2025-06-13 12:16
下一篇 2025-06-10 18:07

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/144597.html