【问题标题】:Problem with Getting value from database to my labels Access Database从数据库获取值到我的标签访问数据库的问题
【发布时间】:2019-05-17 22:19:42
【问题描述】:

大家好,我需要在我的标签上显示我的数据库中的单词,但我遇到了一个问题,它对我不起作用并且它没有显示单词... 我正在使用 Select from 并且它没有显示它......

        string connectionStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\WordssTable.mdb;
    Persist Security Info=False";
    OleDbConnection connectObj = new OleDbConnection(connectionStr);
    connectObj.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connectObj;
    command.CommandText = "SELECT * FROM WordsTable WHERE EnglishWord='" + hebw1.Text + "'";
    command.ExecuteNonQuery();

2

    <form runat="server">
<div id = "Words">
<asp:Label runat="server" id="Engw"></asp:Label>
<br />
<asp:Label id="hebw1" runat="server"></asp:Label>
<asp:Label id="hebw2" runat="server"></asp:Label>
<asp:Label id="hebw3" runat="server"></asp:Label>
<asp:Label id="hebw4" runat="server"></asp:Label>
</div>
</form>

【问题讨论】:

  • 您的样本不完整。你执行命令了吗?您是否使用 OleDbDataReader 返回的数据来更新您的标签?请发帖minimal reproducible example 帮助我们了解您的问题
  • 兄弟我要补充什么?
  • 您可能需要考虑a DataSource control,因为您正在使用网络表单。链接的文档主要演示了使用 MS SQL Server,但差别很小。

标签: c# html asp.net select


【解决方案1】:

首先要做的是在一次性物品周围使用正确的using statement。然后更改您的命令文本以使用参数占位符 (@text) 而不是字符串连接。 (这个绝对不能小觑。参数防止解析错误和sql注入黑客)

现在您可以请求OleDbDataReader 并使用它来使用来自OleDbDataReader 检索到的第一条记录的数据来填充您的标签

string connectionStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\WordssTable.mdb;
Persist Security Info=False";
using(OleDbConnection connectObj = new OleDbConnection(connectionStr))
using(OleDbCommand command = new OleDbCommand())
{
    connectObj.Open();
    command.Connection = connectObj;
    command.CommandText = "SELECT * FROM WordsTable WHERE EnglishWord=@text";
    command.Parameters.Add("@text", OleDbType.VarWChar).Value = hebw1.Text;
    using(OleDbDataReader reader = command.ExecuteReader())
    {
        // Try to read the first record, if any, and then update the labels
        if(reader.Read())
        {
             hebw1.Text = reader["hebw1"].ToString();
             hebw2.Text = reader["hebw2"].ToString();
             hebw3.Text = reader["hebw3"].ToString();
             hebw4.Text = reader["hebw4"].ToString();
        }
   }
}

我假设您的记录包含阅读器索引器使用的列 hebwX,并且这些字段都不是空的。

【讨论】:

    【解决方案2】:

    您的问题是您调用 command.ExecuteNonQuery() 仅返回受影响的行数。 您需要将其更改为

    command.CommandText = "SELECT * FROM WordsTable WHERE EnglishWord='" + hebw1.Text + "'";
    OleDbReader reader = command.ExecuteReader();
    while(reader.Read()){
      // set your label values here
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 1970-01-01
      • 2013-04-17
      • 2011-01-01
      • 2019-11-12
      • 2014-11-03
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多