首页 > 解决方案 > C#:使用文本框和按钮从 Windows 窗体执行查询

问题描述

如何更改我的代码,以便搜索表的特定列?

我想在 TextBoxes 中写入请求的列值,然后在按下按钮时执行请求。

private async void button26_Click(object sender, EventArgs e)
{
    if (label77.Visible) label77.Visible = false;
    if (!string.IsNullOrEmpty(textBox62.Text) && !string.IsNullOrEmpty(textBox62.Text))
    {
        SqlCommand command = new SqlCommand("INSERT INTO [Policlinic] ('id_Policlinic', 'Name', 'Address', 'Phone') VALUES (" + textBox62 + ", '" + textBox62 + "', '" + textBox62 + "','" + textBox62 + "')", sqlConnection);
        command.Parameters.Add("@id_Policlinic", SqlDbType.Int); command.Parameters["@id_Policlinic"].Value = Convert.ToInt32(textBox62.Text, 4);
        command.Parameters.AddWithValue("Name", textBox62.Text);
        command.Parameters.AddWithValue("Address", textBox62.Text);
        command.Parameters.AddWithValue("Phone", textBox62.Text);
        await command.ExecuteNonQueryAsync();
    }
    else
    {
        label77.Visible = true;
        label77.Text = "Поля должны быть заполнены!";
    }
}

有什么想法吗?

标签: c#sqlsql-serverwinformstsql

解决方案


尝试这个:

private async void button26_Click(object sender, EventArgs e)
{
    //why check the SAME textbox twice?
    // You should give MEANINGFUL NAMES to your controls, rather than leaving them at the default
    if (string.IsNullOrEmpty(textBox62.Text) || string.IsNullOrEmpty(textBox62.Text)) 
    {
        label77.Visible = true;
        label77.Text = "Поля должны быть заполнены!";
        return;
    }
    label77.Visible = false;

    string sql = "INSERT INTO [Policlinic] (Name, Address, Phone) VALUES ( @Name, @Address, @Phone);";

    using (var con = new SqlConnection("connection string here"))
    using (var cmd = new SqlCommand(sql, con))
    {  
        //Use exact database column types and lengths here
        // DON'T trust ADO.Net to guess these types correctly.
        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 20).Value = textBox62.Text;
        cmd.Parameters.Add("@Address", SqlDbType.NVarChar, 80).Value =  textBox62.Text;
        cmd.Parameters.Add("@Phone", SqlDbType.NVarChar, 14).Value =  textBox62.Text;

        con.Open()
        await cmd.ExecuteNonQueryAsync();
    }
}

这里有一些重要的变化:

  1. 不要尝试在SqlConnection整个应用程序中重复使用相同的对象。这会干扰内置的连接池。
  2. 不要相信 ADO.Net 会猜测您的参数类型和长度。
  3. 务必依靠using块来确保您的连接对象已被释放,即使抛出异常也是如此。

如果您仍在学习如何做这些事情,我还建议您暂时删除 async/ await,然后调用ExecuteNonQuery(). 在以“正常”方式工作后将其添加回来。


推荐阅读