gpt4 book ai didi

C# - 更新 SQL 表

转载 作者:行者123 更新时间:2023-12-05 08:41:56 25 4
gpt4 key购买 nike

我想更新我的 sql 表。我在这里搜索并找到了解决该问题的方法。但遗憾的是它只是不会更新数据库。我不知道问题出在哪里。我检查了几次 sql 命令是否写错了,但找不到任何错误或修复了它们,但遗憾的是仍然没有。我想它是在 try block 中的东西,但找不到它。

这是我的代码:

string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);

command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");

}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}

希望有人能帮我找出错误。

编辑:当我尝试它时,它似乎工作正常,因为窗口弹出“workd”但数据库未更改。

最佳答案

正如 Michał Turczyn 在他的 answer 中所写的那样,你的代码有一些问题。
我同意他写的所有内容,但我认为您可能会从看到您的代码应该是什么样子中受益 - 所以现在开始:

var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = @LastName, FirstName = @FirstName, Title = @Title ... ";// repeat for all variables
try
{
using(var connection = new SqlConnection(connetionString))
{
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("@LastName", SqlDbType.NVarChar).Value = Lnamestring;
command.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = Fnamestring;
command.Parameters.Add("@Title", SqlDbType.NVarChar).Value = Titelstring;
// repeat for all variables....
connection.Open();
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
MessageBox.Show($"Failed to update. Error message: {e.Message}");
}

关于C# - 更新 SQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46068791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com