【发布时间】:2020-08-14 15:10:07
【问题描述】:
我正在尝试更新 Episode 表中的 EpisodeId no:117 并且它成功执行但是当我检查表时它没有更新。 int 剧集 ID = 117;
int seriesNumber = 9;
int episodeNumber = 13;
string episodeType = "abnormal episode";
string title = "Reconsideration";
string notes = "recuring behaviour";
//connectionString
string connectionString = "data source=LAPTOP-VLO4EFFQ\\MSSQLSERVER01; database=DoctorWho; integrated Security=True;";
//connection using
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
Console.WriteLine("Connection sucessfull");
string query = "UPDATE tblEpisode " +
"(SeriesNumber, EpisodeNumber, EpisodeType, Title, Notes)" +
"(SET SeriesNumber=@SeriesNumber, EpisodeNumber=@EpisodeNumber, EpisodeType=@EpisodeType, Title=@Title, Notes=@Notes)" +
"(WHERE EpisodeId=@EpisodeId)";
using (SqlCommand command = new SqlCommand(query, conn))
{
//updating data in the sql table with the initial variables
command.Parameters.Add("@EpisodeId", System.Data.SqlDbType.Int).Value = episodeId;
command.Parameters.Add("@SeriesNumber", System.Data.SqlDbType.Int).Value = seriesNumber;
command.Parameters.Add("@EpisodeNumber", System.Data.SqlDbType.Int).Value = episodeNumber;
command.Parameters.Add("@EpisodeType", System.Data.SqlDbType.NVarChar).Value = episodeType;
command.Parameters.Add("@Title", System.Data.SqlDbType.NVarChar).Value = title;
command.Parameters.Add("@Notes", System.Data.SqlDbType.NVarChar).Value = notes;
}
conn.Close();
Console.WriteLine("connection is closed!!");
}
【问题讨论】:
-
您如何知道查询正确执行?您的更新语句的格式似乎很奇怪,我希望
Update table set column = value where Id = x没有完整的第二行和所有这些括号。 -
你没有执行命令,使用
command.ExecuteNonQuery()参考链接docs.microsoft.com/en-us/dotnet/framework/data/adonet/… -
赫曼特所说的。使用阅读器或命令执行查询。ExecuteNonQuery
-
@HemantHalwai 是对的,你也应该执行命令。但是 ExecuteReader 看起来很奇怪,因为你什么都没读。
-
另外,为什么 SET 和 WHERE 在括号中?而且我没有看到这里定义的 episodeId。
标签: c# sql sql-update sqlconnection c#-datatable