我正在尝试通过控制台C#更新sql数据库中主键列中的值。
我在Internet上搜索了几个小时,但仍然无法解决为什么我的数据库不会更新到让事情变得更糟我没有遇到任何错误。
static void editMONDAY()
{
SQLCONN.Open();
var TIME = DateTime.Now;
SqlCommand cmd0 = new SqlCommand("SELECT * FROM dbo.mondayTable", SQLCONN);
SqlDataReader reader = cmd0.ExecuteReader();
while (reader.Read())
{
int n = 0;
Console.WriteLine("------------------------------------------------------------");
Console.WriteLine(" [" + reader.GetValue(n).ToString() + " TIMES] [TEACHER / CLASSROOM] MONDAY " + TIME.ToString("HH:mm:ss"));
Console.WriteLine("------------------------------------------------------------");
for (int i = 1; i < reader.FieldCount; i++)
{
Console.WriteLine(i +" - " + reader.GetName(i) + " " + reader.GetValue(i));
}
}
SQLCONN.Close(); //stop memory leaks??? wait and see!
Console.WriteLine("Which group would you like to edit?");
string Group = Console.ReadLine();
Console.WriteLine("Enter the groups new name or same name is nothing is to change");
string newGroup = Console.ReadLine();
Console.WriteLine("Which classtime would you like to edit?");
string Class = Console.ReadLine();
Console.WriteLine("Enter the new teacher and classroom number");
string newClass = Console.ReadLine();
//SQLCONN.Open();
//update ID (SAT)
using (SqlCommand cmd =
new SqlCommand("UPDATE mondayTable SET SAT=@SAT where SAT=@"+Group, SQLCONN))
{
cmd.Parameters.AddWithValue("@"+Group, newGroup);
cmd.ExecuteNonQuery();
}
Console.ReadKey();
menu();
更新:这是我希望更新的表。
CREATE TABLE [dbo].[mondayTable] (
[SAT] VARCHAR(50) NOT NULL,
[09:00-09.40] VARCHAR (MAX) NULL,
[10:10-10:50] VARCHAR (MAX) NULL,
[11.00-11:40] VARCHAR (MAX) NULL,
[11:50-12:30] VARCHAR (MAX) NULL,
[12:40-13:20] VARCHAR (MAX) NULL,
[13:30-14:10] VARCHAR (MAX) NULL,
[14:20-15:00] VARCHAR (MAX) NULL,
[15:10-15:50] VARCHAR (MAX) NULL,
[16:00-16:40] VARCHAR (MAX) NULL,
[16:50-17:30] VARCHAR (MAX) NULL,
[17:40-18:20] VARCHAR (MAX) NULL,
[18:30-19:10] VARCHAR (MAX) NULL,
[19:20-20:00] VARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([SAT] ASC)
);
答案 0 :(得分:0)
您的更新查询需要两个参数@SAT和@Group,但您只提供一个参数 我不确定您要为参数SAT设置什么值。
但是,如果您想使用newGroup更改SAT(Group)的旧值,那么就应该添加它。
// Do not close before or reopen here
SQLCONN.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE mondayTable SET SAT=@SAT where SAT=@"+Group, SQLCONN))
{
cmd.Parameters.AddWithValue("@SAT", newGroup);
cmd.Parameters.AddWithValue("@"+Group, Group);
cmd.ExecuteNonQuery();
}