
假设在服务器上存在一个名为'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
立即学习“Python免费学习笔记(深入)”;
sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
现在,使用游标对象的execute()方法执行此查询
cursor.execute(sql)
如果您检查员工表的内容,将会显示添加了一条新记录。
以上就是如何在MySQL中插入Python对象?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号