我想创建一些东西,如果我的数据库的那一列有数据,那么它将提示数据。但是,如果该列为空,则会显示另一条消息。
try
{
string myConnectionString1;
myConnectionString1 = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection1 = new MySqlConnection(myConnectionString1);
MySqlCommand cmd1 = new MySqlCommand();
EncodingProvider ppp1;
ppp1 = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp1);
cmd1.CommandType = CommandType.Text;
string sqlStr1 = "Select arm from assign where userId=@name";
cmd1.Parameters.AddWithValue("@name", txtValue.Text);
cmd1.CommandText = sqlStr1;
cmd1.Connection = connection1;
connection1.Open();
MySqlDataReader reader = cmd1.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
string databaseLine = (reader["arm"].ToString());
txtExercise.Text += databaseLine + " (Incomplete)\n";
if(databaseLine == null)
{
txtExercise.Text += "No exercises";
}
}
else
{
txtExercise.Text += "There are no available exercise.";
}
connection1.Close();
}
这是我所做的,但是它提示我一个错误:字符串databaseLine =(reader [“ arm”]。ToString());
异常详细信息:System.NullReferenceException:没有对象引用 设置为对象的实例。
我该如何解决?
答案 0 :(得分:0)
在使用toString()之前检查null
string s = String.IsNullOrEmpty(reader [“ arm”])?“此处为Sometext”:reader [“ arm”]。ToString();
答案 1 :(得分:0)
您需要检查db null值。转换为字符串
之前 string databaseLine = reader["arm"].Equals(DBNull.Value) ? "Empty" : reader["arm"].ToString()