mysql 语句 自动,mysql,准备好的语句和自动类型转换

I am getting different results performing the exact same query using regular statements and prepared statements, and I think it's a type conversion bug.

mysql> show columns from server where field = "vlan";

+-------------+--------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------------+--------+------+-----+---------+-------+

| vlan | int(5) | YES | MUL | NULL | |

+-------------+--------+------+-----+---------+-------+

mysql> select hostname from server where `vlan` = '184.182' limit 1;

Empty set (0.00 sec)

mysql> prepare stupid from "select hostname from server where `vlan` = ? limit 1";

Query OK, 0 rows affected (0.00 sec)

Statement prepared

mysql> set @vlan = '184.182';

Query OK, 0 rows affected (0.00 sec)

mysql> execute stupid using @vlan;

+-------------------+

| hostname |

+-------------------+

| web20.servers.com |

+-------------------+

1 row in set (0.00 sec)

the real value of vlan is 184

it looks like the way mysql is handling type conversions is different for prepared statements and regular statements? does that make sense? how do i fix this?

解决方案

The expected data type of prepared statement parameters is determined upon statement preparation, and type conversion to that data type takes place prior to statement execution.

In your example, an integer parameter is expected; therefore the provided string is cast to an integer (184) before the statement is executed, and the comparison between the integer column vlan and the parameter is successful for the matching record.

The "regular" statement, by contrast, compares the integer column with a string; therefore the arguments are compared as floating point numbers, and no record has a matching vlan.

To avoid this situation, ensure that the data type cannot be determined upon preparation (or that the determined data type does not lose any information) - for example:

prepare not_so_stupid from

"select hostname from server where `vlan` = CAST(? AS CHAR) limit 1"

;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值