c# - 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 = "Поля должны быть заполнены!";
}
}
有什么想法吗?
解决方案
尝试这个:
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();
}
}
这里有一些重要的变化:
- 不要尝试在
SqlConnection
整个应用程序中重复使用相同的对象。这会干扰内置的连接池。 - 不要相信 ADO.Net 会猜测您的参数类型和长度。
- 务必依靠
using
块来确保您的连接对象已被释放,即使抛出异常也是如此。
如果您仍在学习如何做这些事情,我还建议您暂时删除 async
/ await
,然后调用ExecuteNonQuery()
. 在以“正常”方式工作后将其添加回来。
推荐阅读
- bash - AWK -F 打印除最后一条记录以外的所有记录
- java - Android Margin 和 Padding 不适用于 ScrollViews 中的 RecyclerViews
- limesurvey - LimeSurvey - 按 group_order 呈现问题组,然后按 question_order 呈现问题
- regex - 将输入中的至少两个单词与语句匹配
- laravel - 如何在 Laravel 查询中使用 postgres 的 dblink 功能
- hibernate - 使用 XML 文件的 Hibernate 继承映射
- javascript - 使用 chrome.webRequest.onBeforeRequest 编辑表单数据
- asp.net - tfs build 中的“没有与搜索模式匹配的文件”
- php - PHP x时间过去隐藏mysql值
- angular - 插入记录时 Angular2 时间不正确。如何征收 GTM+2.00?