如何在MySQL中插入Python对象?

WBOY
发布: 2023-08-24 14:05:05
转载
1020 人浏览过

如何在MySQL中插入Python对象?

假设在服务器上存在一个名为'test'的MySQL数据库,并且还创建了一个名为employee的表。让这个表有五个字段:fname,lname,age,gender和salary。

假设我们想要将一个包含以下记录数据的元组对象插入到Msql数据库中。

t1=('Steven', 'Assange', 21, 'M', 2001)
登录后复制

To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements

import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
登录后复制

Next step is to set up the insert query using data in the tuple

sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
登录后复制

现在,使用游标对象的execute()方法执行此查询

cursor.execute(sql)
登录后复制

如果您检查员工表的内容,将会显示添加了一条新记录。

以上是如何在MySQL中插入Python对象?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!