如何在 C# 中使用 MessageBox 打印 SQL 查询

How do I print SQL query using MessageBox in C#

从昨天开始我就被这个问题困扰了。我创建了一个按钮,单击该按钮会显示来自 SQL 服务器 table 的结果。我想到了使用 MessageBox 来打印这些结果,或者是否有任何其他方式来打印结果?

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
        SqlCommand command = new SqlCommand("SELECT * FROM Products", con);

        con.Open();

        SqlDataReader reader = command.ExecuteReader();
        command.ExecuteNonQuery();

        con.Close();
    }
    catch (Exception es)
    {
        MessageBox.Show(es.Message);
    }
}

我尝试了不同的方法,但都没有用。我真的被困住了。如果您需要更多详细信息,请告诉我。预先感谢您的帮助

您需要使用 SqlDataReader 迭代 行 returned,从每一行中提取您需要的内容,然后将其显示到最终用户。

我稍微修改了您的代码,使其更安全(using 块!),并且我将查询修改为 return 只有产品名称(假设您有),因为您不能确实在消息框中显示 整行....

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
        string query = "SELECT ProductName FROM Products;";

        using (SqlConnection con = new SqlConnection(connectionString))
        using (SqlCommand command = new SqlCommand(query, con))
        {
            con.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
               while (reader.Read()) 
               {
                    string productName = reader.GetFieldValue<string>(0);
                    MessageBox("Product is: " + productName);
               }

               reader.Close();
            }

            con.Close();
        }
    }
    catch (Exception es)
    {
        MessageBox.Show(es.Message);
    }
}

添加一个 datagridview 控件以显示多行并尝试此代码并将其重命名为您想要的名称并将此 YourDataGridVeiwName 替换为您为 datagridview 控件设置的名称并尝试下面的代码

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
        string query = "SELECT ProductName FROM Products;";

        using (SqlConnection con = new SqlConnection(connectionString))
        using (SqlCommand command = new SqlCommand(query, con))
        {
            con.Open();

            using (SqlDataAdapter sda = new SqlDataAdapter(command))
            {

              DataTable dt = new DataTable(); 
              sda.Fill(dt);
              YourDataGridVeiwName.DataSource= dt;
             }

            con.Close();
        }
    }
    catch (Exception es)
    {
        MessageBox.Show(es.Message);
    }
}