sql commnad不工作在c中的select语句#
我想执行下面的代码使用sql命令来获取输出并将其存储在一个整数变量。代码返回-1为空值插入,这是很好的。sql commnad不工作在c中的select语句#
但是,当数据库表中存在值并且给出正确的输入时,代码将再次返回相同的-1值。
有人能指出我正确的方向吗?
try {
con.Open();
SqlCommand cmd1 = new SqlCommand(@"(Select ERSConversionFactorID FROM " + schemaName + "[ERSConversionFactors] WHERE [ERSConversionFactor_CF] = @conversionvalue AND [ERSConversionFactor_Desc] = @convDescription)", con);
if (comboBox_ConfacValue.Text == "")
{
cmd1.Parameters.Add("@conversionvalue", SqlDbType.NVarChar, 160).Value = DBNull.Value;
}
else
{
cmd1.Parameters.Add("@conversionvalue", SqlDbType.NVarChar, 160).Value = comboBox_ConfacValue.Text;
}
if (combobox_conversionDescription.Text == "")
{
cmd1.Parameters.Add("@convDescription", SqlDbType.NVarChar, 160).Value = DBNull.Value;
}
else
{
cmd1.Parameters.Add("@convDescription", SqlDbType.NVarChar, 160).Value = combobox_conversionDescription.Text;
}
string sql = "Select ERSConversionFactorID FROM " + schemaName + "[ERSConversionFactors] WHERE [ERSConversionFactor_CF] = @conversionvalue AND [ERSConversionFactor_Desc] = @convDescription)";
int conversionvalue = cmd1.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
感谢
ExecuteNonQuery
不打算被用来从查询返回值。它执行查询,但它只返回受INSERT,UPDATE或DELETE语句影响的行数。
如果您看一下MSDN上ExecuteNonQuery页面上的REMARKS部分,您会发现返回值为-1的原因。
使用SELECT命令,您可以使用ExecuteReader或更好的ExecuteScalar,如果您只是希望SELECT语句检索到第一行的第一列。
然而,因为你的查询有一个WHERE语句,可能导致没有检索到的行,你应该对ExecuteScalar
object result = cmd1.ExecuteScalar();
if(result != null)
{
int conversionvalue = Convert.ToInt32(result);
.....
}
真棒感谢它的工作信息...我将这标记为答案:) –
返回值增加检查空尝试的ExecuteScalar
int conversionvalue = cmd1.ExecuteScalar();
您需要对单个值使用ExecuteReader或ExecuteScalar。在这种情况下,我会使用一个ExecuteReader,因为似乎没有人会一直返回单个行。
int? conversionvalue = null; // this will stay null if there is nothing read back
using(var reader = cmd1.ExecuteReader()) { // place the use of the reader in a using block to ensure it is cleaned up
if(reader.Read()) // reader will return true if a record can be read. if you have multiple records you can turn the if into an while loop
conversionvalue = reader.GetInt32(0); // read the value at ordinal position 0 as an int32
}
确实,内部ExecuteScalar使用ExecuteReader,但看看[MSDN上的ExecuteScalar页面](https ://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx)或甚至[在StackOverflow](http://stackoverflow.com/questions/2400005/does-execucalar-have-any-advantage-over-exec) – Steve
@Steve - 谢谢,我知道。我提到ExecuteScalar对于单个值是可以的,但我的示例包含了ExecuteReader,因为select中的语法。如果它是'SELECT TOP 1 ...'或'SELECT COUNT()'或其他表明总是返回1个值(或空值)的东西,那么我也会以'ExecuteScalar'为例(或者根本没有回答,因为已经有ExecuteScalar已经有两个很好的答案(你的和techspider))。 – Igor
你需要学习这一点 - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx?f= 255&MSPPError = -2147217396 – techspider