Python MySQL:使用默认值选择

2024-04-24 23:13:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据库

CREATE TABLE `ip` (
  `idip` int(11) NOT NULL AUTO_INCREMENT,
  `ip` decimal(45,0) DEFAULT NULL,
  `mask` int(11) DEFAULT NULL,
  PRIMARY KEY (`idip`),
  UNIQUE KEY `ip_UNIQUE` (`ip`)
)

我在这张桌子上做了些插入

但是当我尝试在python上执行时:

^{pr2}$

我得到以下错误:

    Inserting routes into table routes (1/377)...('insere_tabela_routes: Error on insertion at table routes, - SQL: ', 'select idip from ip where ip=0 and mask=DEFAULT')
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

有人知道问题出在哪里吗?在


Tags: thekeyipdefaultsqlyourtablemask
2条回答

^{} uses ^{} instead of ^{} as the parameter marker,但您使用Python字符串格式来规避它。试试这个:

sql = "select idip from ip where ip=%s and mask=%s"
cursor.execute(sql, (long(next_hop), 'DEFAULT'))
idnext_hop = cursor.fetchone()[0]

您正在使用参数对查询字符串进行修改,而不是将它们作为参数传入。代码应该如下所示:

sql = "select idip from ip where ip = ? and mask = ?"
cursor.execute(sql, (long(next_hop), 'DEFAULT'))
idnext_hop = cursor.fetchone()[0]

换句话说,您希望查询引擎对查询进行替换。您不希望Python对查询字符串进行替换。在

相关问题 更多 >