C#中对象不能从DBnull转换为其他类型

回答好了继续加20分

从数据库里读数据,如果类型可空,要先判空,特别是int/datetime
string time;
if(!dataRow.IsNull("addTime")){
time=dataRow.Field<DateTime>("addTime");

}

如果是写入,不能写入null要写入DBNull

string name;
if(name==null)
cmd.AddParameter("name",DBNull.Value);
else
cmd.AddParameter("name",name)
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-08-15
select
max(themeNum)
from
Forumtheme
执行的结果是
NULL
也就是
要么
Forumtheme
一条记录也没有
要么
Forumtheme
表里面
themeNum
的数据都是
NULL
int
count
=
Convert.ToInt32(cmd.ExecuteScalar());
//提示出错
count++;
修改为:
int
count
=
0;
Object
tmpVal
=
cmd.ExecuteScalar()
if(
tmpVal
!=
DBNull
)
count
=
Convert.ToInt32(
tmpVal
);
)
count++;
第2个回答  2010-06-28
楼上正解
鉴定完毕,数据库的null要用DBNULL.Value
而不是C#的null
第3个回答  2020-02-19
SqlConnection
con
=
DB.CreateConnectionForum();
con.Open();
SqlCommand
cmd
=
new
SqlCommand("select
max(themeNum)
from
Forumtheme",
con);
int
count
=
0;
object
c
=
cmd.ExecuteScalar()
;
if(c
!=
null)
count
=
Convert.ToInt32(c);
count++;
con.Close();
.....
第4个回答  推荐于2016-07-04
{
byte[] EDS = new byte[183];
EDS[0] = 0x82; // emm table id
EDS[1] = 0x40; //
EDS[2] = 0x3f;
EDS[3] = 0x02;// emm secton length
byte[] groupid = HexStrToHexBytes(dr["Group_name"].ToString());
EDS[4] = groupid[0];
EDS[5] = groupid[1];
// emm secton length
//发送emm

string strConn = "Data Source=127.0.0.1;Initial Catalog=yz;User ID=sa;Password=sa123456";
SqlConnection ConnAcc = new SqlConnection(strConn);
string strSQL = "SELECT SGK FROM Group_SGK3 ";
SqlDataAdapter de = new SqlDataAdapter(strSQL, ConnMdb);
try
{
//da.Fill(dt);
dtData.Clear();
de.Fill(dtData);
}
catch
{
break;
}

for (int n = 0; n < 7; n++)
{
int GK;
foreach (DataRow rdr in dtData.Rows)
{

int SGK = Convert.ToInt32(rdr["SGK"]);
GK = SGK << n;

if (Convert.ToBoolean(rdr["state1"]))
{

byte[] gk = new byte[8];
Array.Copy(HexStrToHexBytes(GK.ToString()), 0, gk, 7, 1);

;
SKeyValue = SKeyValue1;
byte[] EncryptSk = EncryptDES(SKeyValue, gk);

EDS[6] = 0x01;
Array.Copy(EncryptSk, 0, EDS, 7, EncryptSk.Length);
//Thread.Sleep(5);
}
else
{

EDS[6] = 0x01;

EDS[7] = 0xff;
EDS[8] = 0xff;
for (int i = 9; i < 15; i++)
{
EDS[i] = 0x00;

}

}
相似回答