-1 c# sql sql-server max
我试图获取返回的MAX值,但它始终返回0。
string stateValue = "CA";
SqlCommand cmd = new SqlCommand("SELECT MAX(Population) FROM TestData WHERE State=" + stateValue);
cmd.Parameters.Add("@Population", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
DBConnection.Instance.execNonQuery(cmd);
int population = (int)cmd.Parameters["@Population"].Value;
Run Code Online (Sandbox Code Playgroud)
在DBConnection课堂上,这是execNonQuery函数:
public int execNonQuery(string sCmd, CommandType cmdType)
{
SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
cmd.CommandType = cmdType;
try
{
m_sqlDataBase.Open();
}
catch { }
return cmd.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)
参数方向与存储过程一起使用。在这里,您只是在执行一个查询。您需要使用SqlCommand.ExecuteScalar方法,因为您只会返回一个结果。它返回一个,object因此您必须int先将其转换为。
另外,您的代码正在使用字符串连接来创建SQL查询,并且它容易发生SQL注入。还可以考虑在“命令和连接”中使用using语句。
using (SqlCommand cmd = new SqlCommand("SELECT MAX(Popluation) FROM TestData WHERE State=@state"))
{
//Associate connection with your command an open it
cmd.Parameters.AddWithValue("@state", stateValue);
int populuation = (int)cmd.ExecuteScalar();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5857 次 |
| 最近记录: |