Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用c更新SQL Server中的最后一条记录_C#_Sql Server - Fatal编程技术网

C# 如何使用c更新SQL Server中的最后一条记录

C# 如何使用c更新SQL Server中的最后一条记录,c#,sql-server,C#,Sql Server,我试图更新SQL Server数据库表中的最后一条记录,但没有任何更改我不知道出了什么问题,有人能帮我吗 这是我的密码 conn.Open(); SqlCommand sq = new SqlCommand("update Hodor_data set leaving_time = ('" + dateTimePicker1.Value.ToString() + "') where mil_no = '" +textBox1.Text+ "' and times = (select max(ti

我试图更新SQL Server数据库表中的最后一条记录,但没有任何更改我不知道出了什么问题,有人能帮我吗

这是我的密码

conn.Open();
SqlCommand sq = new SqlCommand("update Hodor_data set leaving_time = ('" + dateTimePicker1.Value.ToString() + "') where mil_no = '" +textBox1.Text+ "' and times = (select max(times) from Hodor_data ", conn);
sq.ExecuteNonQuery();
conn.Close();
我的数据库是


这是未经测试的,但希望能满足您的要求:

// You might want to consider making your SQL type a DateTime of 
// some sort to prevent invalid DateTime VARCHAR's from being 
// stored in your leaving_time and arrival_time columns.
var leavingTime = dateTimePicker1.Value.ToString();

// Presumably you've already done validation to make sure
// textBox1.Text contains a valid Int32 value.
var milNo = int.Parse(textBox1.Text);

// You can put the SQL out here on a multi-line string literal
// to make it more readable.  Also notice how it uses parameters
// instead of string concatenation.
var sql = @"
UPDATE Hodor_data 
SET leaving_time = @LeavingTime
WHERE 
    mil_no = @MilNo AND 
    times = 
    (
        SELECT MAX(times) 
        FROM Hodor_data
    )
";

conn.Open();
SqlCommand sq = new SqlCommand(sql, conn);
sq.Parameters.AddWithValue("@LeavingTime", leavingTime);
sq.Parameters.AddWithValue("@MilNo", milNo);
sq.ExecuteNonQuery();
conn.Close();

也可以考虑使用一个使用来管理关闭你的SQL连接,除非你需要重用这个对象。

string sql = "update Hodor_data set leaving_time = '"+dateTimePicker1.Value.ToString()+"' where mil_no = "+textBox1.Text+" and times = (select max(times) from Hodor_data)";

SqlCommand sq = new SqlCommand(sql, conn);

如果多条记录具有时间值,则会更新多条记录。

此处缺少您的记录;从Hodor_data Side中选择maxtimes注意:您可能想研究sql injection.thax berkay,但每次我进行此处理时它都会更新,在varchar字段中存储日期/时间是一个基本错误,我指的不仅是最大时间,而且是所有时间