c#不识别空单元格使用SQL,oleDB

本文关键字:SQL oleDB 单元格 识别 | 更新日期: 2023-09-27 18:17:07

当我试图从我的访问表中获得一个值,单元格是空的,我得到这个错误:

系统。InvalidCastException:指定的类型转换无效。

当我试图从三列中获取信息时发生。它可能在单元格中没有任何值,但在triplet1的列中必须有。这是我写的部分代码。

public Codons(string name)
{
    this.start = false;
    this.end = false;
    this.dataconnection = new OleDbConnection();
    this.dataconnection.ConnectionString =              "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:''Projects_2012''Project_Noam''Access''myProject.accdb";
    this.dataconnection.Open();
    string sql = "SELECT tblCodons.codonsCodon1, tblCodons.codonsCodon3, "+
    "tblCodons.codonsTriplet1, tblCodons.codonsTriplet2, tblCodons.codonsTriplet3, "+
    "tblCodons.codonsTriplet4, tblCodons.codonsTriplet5, tblCodons.codonsTriplet6, "+
    "tblCodons.codonsFullName, tblCodons.codonsStart, tblCodons.codonsEnd"
    +" FROM tblCodons"
    +" WHERE tblCodons.codonsFullName=?";
    OleDbCommand mycomm = new OleDbCommand(sql, dataconnection);
    mycomm.Parameters.AddWithValue("codonsFullName", name);
    OleDbDataReader dataReader = mycomm.ExecuteReader();
    dataReader.Read();
    this.codon1 = dataReader.GetString(0);
    this.codon3 = dataReader.GetString(1);
    this.triplet1 = dataReader.GetString(2);
    if (dataReader.GetString(3) == "")
        this.triplet2 = "     ";
    else
    this.triplet2 = dataReader.GetString(3);
    if (dataReader.GetString(4) == "")
        this.triplet3 = "     ";
    else
    this.triplet3 = dataReader.GetString(4);
    if (dataReader.GetString(5) == "")
        this.triplet4 = "     ";
    else
    this.triplet4 = dataReader.GetString(5);
    if (dataReader.GetString(6) == "")
        this.triplet5 = "     ";
    else
    this.triplet5 = dataReader.GetString(6);
    if (dataReader.GetString(7) == "")
        this.triplet6 = "     ";
    else
    this.triplet6 = dataReader.GetString(7);
    this.fullName = dataReader.GetString(8);
    this.start = dataReader.GetBoolean(9);
    this.end = dataReader.GetBoolean(10);
    dataReader.Close();

我也试过用null代替"。

TNX的帮助!

c#不识别空单元格使用SQL,oleDB

设置字符串属性为(dataReader[3] as string) ?? " "。当数据库字段为空时,类型为DBNull,值为DBNull.Value,而不是类型为string,值为null

您也可以在调用GetString之前使用dataReader[3] == DBNull.Value这样的条件来检查字段是否为空。

在你的代码示例中,你正在检查像这样的东西

  if (dataReader.GetString(3) == "")
      this.triplet2 = "     "; 

我建议使用== string.empty;或使用isNullOrEmpty()方法。Null &空

这里有this.triplet2 = dataReader.GetString(3);试着像这样转换为对象

this.triplet2 = (dataReader.GetString(3) as object) ?? DBNull.Value; 

DBNull也是你最好的选择