登录
首页 >  数据库 >  MySQL

如何在MySQL中插入Python对象?

来源:tutorialspoint

时间:2023-08-25 14:46:05 434浏览 收藏

目前golang学习网上已经有很多关于数据库的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《如何在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对象?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!

声明:本文转载于:tutorialspoint 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>