已经有人发过类似问题:http://topic.csdn.net/t/20040722/13/3199585.html
public int GetCurrentIndentity()
{
int indentity=0;
//@@IDENTITY
string str="select @@identity";
try
{
SqlCommand com=new SqlCommand(str,CDatabase.Connect);
indentity=(int)com.ExecuteScalar();<---出错指定的转换无效???
}
catch(SqlException ee)
{
this.ErrorMessage=ee.Message;
}
return indentity;
} 结论是这种情况是必须得用Convert.ToInt32()来解决,原因是什么呢?select @@identity出来的也是数字啊
假如ExecuteScalar是用泛型实现的,就像这样public T ExecuteScalar<T>()
{
T temp = default(T); object obj = this.ExecuteScalar();
if ((obj == null) || (obj == DBNull.Value))
{
return temp;
}
temp = (T)obj;
return temp;
}
这时候如果数据库里返回的是select @@identity,调用时T是int,当然还是会出现“指定的转换无效”的错误了,
这时是不是只能用typeof(T)来特别判断一下T是System.Int32的情况了?有更好的办法吗?
public int GetCurrentIndentity()
{
int indentity=0;
//@@IDENTITY
string str="select @@identity";
try
{
SqlCommand com=new SqlCommand(str,CDatabase.Connect);
indentity=(int)com.ExecuteScalar();<---出错指定的转换无效???
}
catch(SqlException ee)
{
this.ErrorMessage=ee.Message;
}
return indentity;
} 结论是这种情况是必须得用Convert.ToInt32()来解决,原因是什么呢?select @@identity出来的也是数字啊
假如ExecuteScalar是用泛型实现的,就像这样public T ExecuteScalar<T>()
{
T temp = default(T); object obj = this.ExecuteScalar();
if ((obj == null) || (obj == DBNull.Value))
{
return temp;
}
temp = (T)obj;
return temp;
}
这时候如果数据库里返回的是select @@identity,调用时T是int,当然还是会出现“指定的转换无效”的错误了,
这时是不是只能用typeof(T)来特别判断一下T是System.Int32的情况了?有更好的办法吗?
和Insert一起使才有效果..
单独执行返回NULL所以报错是正常的.
可以通过判断com.ExecuteScalar()的返回值类型来做具体的操作.. int intValue = 0;
SqlConnection conn = new SqlConnection(@"Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=db1;Data Source=.");
SqlCommand com = new SqlCommand("select @@IDENTITY;",conn);
conn.Open();
object o = com.ExecuteScalar();
if (o.GetType().FullName == "System.DBNull")
{
intValue = -1;
}
else if (o.GetType().FullName == "System.Int32")
{
intValue = Convert.ToInt32(o);
}
else {
//...
}
conn.Close();
conn.Dispose();
if(o != DBNull.Value) {
return (int)o;
}