执行数据库命令返回值的问题,兄弟们来看
主要功能是取得表里面的最大id值,然后加1,返回
public class GetId
{
public int id;
private string TN;
private string ConnStr;
private SqlConnection _Conn;
private SqlCommand _Comm;
private string strComm;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="TableName">表名</param>
public GetId(string TableName)
{
TN = TableName;
strComm = "select max(id)+1 from "+TN;
}
/// <summary>
/// 打开数据库读取最大id
/// </summary>
private void getDBId()
{
ConnStr = System.Configuration.ConfigurationSettings.AppSettings["strConn"];
_Conn = new SqlConnection(ConnStr);
_Conn.Open();
_Comm = new SqlCommand(strComm,_Conn);
try
{
id = (int)_Comm.ExecuteScalar();
_Conn.Close();
}
catch
{
_Conn.Close();
}
}
public int OutPut()
{
getDBId();
return id;
}
}
这么写编译没问题,运行就有问题了。得不到id的值。
如果不加try 就是这句id = (int)_Comm.ExecuteScalar();有问题!
怎么回事呀?我该怎么做?