You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB构建SQL替换特殊字符时String.Format报错的解决咨询

问题修复方案

错误根源

代码中的String.Format格式字符串存在语法错误:{0}}多写了一个右大括号,导致Format方法无法正确解析占位符,从而抛出"Input string was not in a correct format"错误。后续构建SQL语句的代码里也存在同样的多括号问题。

修复后的代码

Dim toRemove() As String = {"+", "-", "(", ")", ".", " ", ","}
Dim phone As String = txtPhone.Text.Trim()
Dim append As String = "Phone.Number"
For Each x As String In toRemove
    phone = phone.Replace(x, "")
    ' 修正占位符的多余右括号
    append = String.Format("REPLACE({0}, '{1}', '')", append, x)
Next
If Not String.IsNullOrEmpty(phone) Then
    Dim sqlCondition As String = String.Format("{0} LIKE @Phone", append)
    ' 使用参数化查询规避SQL注入风险
    If String.IsNullOrEmpty(sSQL) Then
        sSQL = sqlCondition
    Else
        sSQL = String.Format("{0} AND {1}", sSQL, sqlCondition)
    End If
    ' 需在执行SQL时补充参数赋值,示例:
    ' cmd.Parameters.AddWithValue("@Phone", phone)
End If

额外优化说明

  • SQL注入防护:原代码直接将用户输入拼接进SQL语句,存在严重安全风险。修复后改用参数化查询(@Phone占位符),需在执行SQL的命令对象中为参数赋值。
  • 格式字符串规范:所有String.Format的占位符需严格遵循{n}格式,避免多余的括号或特殊符号干扰解析。

内容的提问来源于stack exchange,提问作者jp2code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:39:58