ASP.NET 2.0:无法将VarChar转换为Int

Ant*_*ton 1 vb.net sql-server-2005 asp.net-2.0

我有一个ASP.Net表单,它从文本框中获取值:

<asp:TextBox ID="txtID" runat="server" maxlength=9></asp:TextBox>
Run Code Online (Sandbox Code Playgroud)

ID为9个数字.

在抓住它之后,我想将它插入数据库(SQL Server 2005),所以我构建了一个参数化字符串,

'The Query
cmd.CommandText = "insert into table (aid) values ('@aid')"
cmd.Connection = conn

'Grab the value
cmd.Parameters.add("@aid", SqlDBType.Int).value = txtID.text

'Execute!
cmd.Connection.Open()
cmd.ExecuteNonQuery
Run Code Online (Sandbox Code Playgroud)

但是,它不让我.它不断给出以下错误消息:

Conversion failed when converting the varchar value '@aid' to data type int.
Run Code Online (Sandbox Code Playgroud)

所以我尝试过各种各样的事情:

cmd.Parameters.add("@aid", SqlDBType.Int).value = 999999999
cmd.Parameters.add("@aid", SqlDBType.Int).value = Convert.ToInt16(txtID.text)
cmd.Parameters.add("@aid", SqlDBType.Int).value = Convert.ToInt32(txtID.text)
cmd.Parameters.add("@aid", SqlDBType.Int).value = Convert.ToInt64(txtID.text)
Run Code Online (Sandbox Code Playgroud)

什么都行不通.在数据库内部,类型为"int".

有任何想法吗?

Eri*_*ric 5

删除@aid查询中的引号,以便它看起来像这样:

cmd.CommandText = "insert into table (aid) values (@aid)"
Run Code Online (Sandbox Code Playgroud)

否则,您将发送代码混合消息.参数永远不会用引号括起来.如果它们用引号括起来,它们就是字符串文字.此外,在纯SQL中,数字不是用引号括起来的,而是用文本值(varchar等等)括起来的.因此,删除引号,参数应该没有问题被创建.

参数不会直接插入SQL批发.SQL Server解析了查询后,它们就被填入了.因此,参数应该是独立的,因为如果它们不是,它们将被视为字符串文字.参数化将注意将参数转换为正确的数据类型.有关参数如何在幕后工作的更多信息,请参阅此文章.

  • 即使它是varchar参数,您也可以在引号中包含参数名称. (3认同)