如何在 UWP 应用程序中使用 C# 代码查找和显示 SQL 数据库中的特定数据?

How to find and display specific data in SQL Database with C# code in UWP app?

编辑 2:通过使用 SqlConnection、SqlCommand 和 SqlDataReader 解决

免责声明:我是使用 C# 代码在 SQL 数据库中搜索的初学者,所以我对这个问题几乎一无所知。

我的任务是制作一个桌面应用程序,用于根据产品 ID 在数据库中搜索产品名称。我唯一成功的是通过 Visual Studio 将 SQL 数据库连接到应用程序。 On this picture you can see the clearest description I am able to give.

我完全不知道该尝试什么。我已经看到一些 class 称为 SqlConnection,但同样,我不完全确定它是否能以某种方式帮助我。

我确信这是本网站上发布过的最基本的问题之一,但我完全被困住了,不知道下一步该怎么做。

提前致谢。

编辑:是的,我忘了提及一件非常重要的事情——我将其制作为 UWP 应用程序。对不起。

首先你需要为你的数据库设置一些连接, 将此行添加到您的 web.config 文件

<connectionStrings>
  <add name="myDbConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

然后如果你设计UI部分,那么 单击 UI、

按钮后调用此函数
protected void Button1_Click(object sender, EventArgs e)
    {
        //data soure control that works with sql database
        SqlDataSource sds = new SqlDataSource();
        //get connection string from application's web.config file
        sds.ConnectionString = ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString();
        //create parameters with specified name and values
        sds.SelectParameters.Add("name", TypeCode.String, this.TextBox1.Text);
        //set the sql string to retrive data from the database
        sds.SelectCommand = "SELECT * FROM [myTb] WHERE [name]=@name";
        //retrive data
        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);
        if (dv.Count == 0)
        {
            this.Label1.Text = "No Data Found";
            return;
        }
        else
        {
            GridView1.DataSource = sds;
            GridView1.DataBind();
        }
    }

您的场景请参考Use a SQLite database in a UWP应用文档。它具有使用 Microsoft.Data.SQLite 通过特定 table-命令加载数据库的详细步骤。

searching a name of a product in a database based on its ID.

SELECT * FROM [tb-name] WHERE [id]=@id"


selectCommand.Parameters.AddWithValue("@id", "id-value");