0

应用程序——一个文本块,一个按钮。+ SQL 数据库——一张表。当我单击按钮时,我正在尝试从 sql 读取到文本块,但它不起作用。

private void nextButton_Click(object sender, RoutedEventArgs e)
    {
        GetSqlData();
    }

    private void GetSqlData()
    {
        string connectionString = @"Data Source=Jama-Dharma\sqlexpress;Initial Catalog=Cars;Integrated Security=True";
        SqlConnection sqlConnection = new SqlConnection(connectionString);

        using (sqlConnection)
        {
            string sqlQuery = @"SELECT c.Name FROM CarsCatalog c";
            SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);

            sqlConnection.Open();

            SqlDataReader sqlReader = sqlCommand.ExecuteReader();

            while (sqlReader.Read())
            {
                nameTextBlock.Text = sqlReader.GetString(0);
            }

            sqlConnection.Close();
        }
    }

如何在单击按钮时,从 SQL 中获取下一个 ID 值。

4

2 回答 2

1

乍一看,您的 while 循环似乎只是覆盖了文本块。退出循环后更新文本块文本。尝试类似的东西

 var sb = new StringBuilder();
 while (sqlReader.Read())
 {
     sb.AppendLine(sqlReader.GetString(0));
 }

 nameTextBlock.Text = sb.ToString();
于 2012-08-14T14:43:22.923 回答
0

您可以保存您到现在为止获得的最后一个 ID,并获取大于此保存的 ID 的下一个 ID。例如:

    using (var sqlConnection = new SqlConnection(...))
    {
        string sqlQuery = @"SELECT c.Name,c.ID FROM CarsCatalog c where c.ID > " 
                            + lastID.ToString();
        SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);

        sqlConnection.Open();

        SqlDataReader sqlReader = sqlCommand.ExecuteReader();

        if (sqlReader.Read())
        {
            nameTextBlock.Text = sqlReader.GetString(0);
            lastID = sqlReader.GetInt(1);
        }
    }
于 2012-08-14T14:57:01.557 回答