如何在 C# 中将 ID 作为 Select 查询的变量。 我编写了一个查询,它必须选择具有特定设备类型的所有 ID。
sqlCommand = new SqlCommand("SELECT Id FROM T_Table1 WHERE DeviceType='" + dev + "'" + "", DbConnect());
int id = (int)sqlCommand.ExecuteScalar();
那是异常(exception):
An unhandled exception of type 'System.InvalidCastException' occurred in test.exe
Additional information: Specified cast is not valid.
最佳答案
首先,您必须检查“id”列的数据库类型。如果是 bigint,则使用 long
而不是 int
。
其次,您不应将查询字符串添加到 select 语句中。这使黑客以后可以对您的应用程序或服务运行 sql 注入(inject)。
请将参数与 SqlCommand 对象一起使用。
string sql= "SELECT Id FROM T_Table1 WHERE DeviceType=@dev";
SqlCommand command = new SqlCommand(sql, DbConnect());
command.Parameters.Add("@dev", SqlDbType.Text);
command.Parameters["@dev"].Value = dev;
long id = (long)command.ExecuteScalar();
关于c# - 在c#中选择查询后获取表的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046286/