通过pymysql中cursor.execute()执行insert into 为mysql数据库插入数据时的坑及解决方法 您所在的位置:网站首页 数据库cursors 通过pymysql中cursor.execute()执行insert into 为mysql数据库插入数据时的坑及解决方法

通过pymysql中cursor.execute()执行insert into 为mysql数据库插入数据时的坑及解决方法

2024-03-28 04:21| 来源: 网络整理| 查看: 265

mysql数据库中insert into 插入数据中的坑 正常来说

一般通过

insert into 表名(字段1, 字段2, ...) values (值1, 值2, ...)

就可以将数据插入到该表中,例如: 直接在mysql数据库中操作:

insert into person(name,phone,hire_date,salary) values('张三', '13112345678', '2020-05-21', 15000.0);

通过远程连接数据库插入数据

connect = pymysql.connect( host='xx.xx.xx.xx', port=3306, user='xxx', passwd='xxx', db='boss', charset='utf8' ) sql1 = "insert into City(city_name) values '%s'" % item["city_name"] cursor.execute(sql1) connect.commit() 坑

上面正常的语句怎么看都是没有语法问题的,但这是一般情况而言的。

而这里想要特别说明的是,这样的写法可能会报错,

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

即语法错误。

特别是通过pymysql远程连接数据库,通过cursor游标执行sql1语句的时候,更容易出现这种语法错误。

解决方法

很简单,只需要指定需要将数据插入到哪个库下的哪个表

具体如下:

此处连接的是boss库,是对boss库中的person表插入数据

insert into boss.person(name,phone,hire_date,salary) values('张三', '13112345678', '2020-05-21', 15000.0);

此处连接的是boss库,是对boss库中的City表插入数据

connect = pymysql.connect( host='xx.xx.xx.xx', port=3306, user='xxx', passwd='xxx', db='boss', charset='utf8' ) sql1 = "insert into boss.City(city_name) values '%s'" % item["city_name"] cursor.execute(sql1) connect.commit()

不细心对比的话很不容易发现我做了什么,两端代码的区别在于

在这里插入图片描述 以上就是对insert into 这个坑的解决方法。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有