C# 单击C中的按钮,从用户指定的表中删除一行
我使用的是Visual Studio 2019 Winforms C.NET框架,在Winforms项目中,有一个文本框和一个按钮 当我在文本框中键入参数名称并单击按钮时,我想从名为Serial_Key的表中删除该行C# 单击C中的按钮,从用户指定的表中删除一行,c#,.net,sql-server,visual-studio,winforms,C#,.net,Sql Server,Visual Studio,Winforms,我使用的是Visual Studio 2019 Winforms C.NET框架,在Winforms项目中,有一个文本框和一个按钮 当我在文本框中键入参数名称并单击按钮时,我想从名为Serial_Key的表中删除该行 private void button1_Click(object sender, EventArgs e) { string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn2 = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Serial-Keys] where Serial_Key=@Serial_Key";
sqlconn2.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn2);
sqlcomm.Parameters.AddWithValue("@Serial_Key", SerialKeyBox.Text);
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
sqlcomm.ExecuteNonQuery();
if (dt.Rows.Count > 0)
{
Cursor.Current = Cursors.WaitCursor;
try
{
}
catch (Exception)
{
}
Cursor.Current = Cursors.Default;
}
else
{
MessageBox.Show("Invalid Serial Key!");
label7.Text = "Serial Key Rejected...";
}
}
将select语句更改为delete语句,并删除所有DataAdapter内容,因为只有在查询记录时才需要这样做
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn2 = new SqlConnection(mainconn);
// Use a Delete statement, not a select
string sqlquery = "delete from [dbo].[Serial-Keys] where Serial_Key = @Serial_Key";
sqlconn2.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn2);
// Construct the parameter yourself with the correct datatype and precision
sqlcomm.Parameters.Add(new SqlParameter("@Serial_Key", SqlDbType.VarChar, 32) { Value = SerialKeyBox.Text });
// Remove all the DataAdaptor stuff
// ExecuteNonQuery returns the rows affected
int numberOfRecords = sqlcomm.ExecuteNonQuery();
if (numberOfRecords > 0)
{
// Any code to run on an effective delete
}
else
{
MessageBox.Show("Invalid Serial Key!");
label7.Text = "Serial Key Rejected...";
}
}
如果安装Dapper,则代码变得非常简单:
private async void button1_Click(object sender, EventArgs e)
{
using(var c = new SqlConnection(_connStr))
await c.ExecuteAsync("DELETE FROM dbo.[Serial-Keys] WHERE serial_key = @sk", new { sk = SerialKeyBox.Text });
}
另外,它在运行查询时不会阻塞您的UI
我建议您将字符串mainconn=ConfigurationManager.ConnectionStrings[Myconnection].ConnectionString;转换为一个名为_connStr的类级变量,以帮助整理内容
没有附属关系问题是什么?问题是有人能给我一个解决方案吗。@TERIZOROGAME似乎你已经有了一些解决方案。但我们不知道您目前的解决方案面临什么问题。所以我不确定你在寻找什么样的解决方案。@Dale K完全正确!这就是我想要的!问题是我不想要任何DLL文件。但不管怎样@Dale K解决了我的问题。我不想要任何DLL文件,最好不要使用.net framework;需要从头开始编写一切,数据库驱动程序、图形驱动程序等等,因为你现在正在使用System.Data.dll,甚至。。。或者,如果您正在寻找某种方法来创建一个自包含的单个exe,但希望利用已经存在的代码written@Caius我是说没有第三方DLL。只有微软因为微软从不使用第三方DLL?我是说内置的dllsI对它进行了升级,但没有显示,因为我不是15+代表。