我使用 SQL Server 2012 和 VS 2012。我有一个包含以下数据的表:
TagID SessionID ScanningTime
int nvarchar datetime
---------------------------------------
4820427 Test1 2013-08-16 14:20:17.447
我创建了一个 UPDATE 查询以将 DGV 中所做的任何更改(添加的任何记录或编辑的现有记录)保存回 SQL DB。
因此,例如,我将添加一条新记录并将现有记录编辑为如下所示:
TagID SessionID ScanningTime
int nvarchar datetime
---------------------------------------
4820000 Test1 2013-08-16 14:20:17.447
3242341 Test1 2013-08-16 14:20:17.447
并单击按钮更新数据库:
private void UpdateBtn_Click(object sender, EventArgs e)
{
DataTable queryResult = new DataTable();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int tagID = Convert.ToInt32(row.Cells["TagID"].Value);
string sessionID = Convert.ToString(row.Cells["SessionID"].Value);
DateTime ScanningTime = Convert.ToDateTime(row.Cells["ScanningTime"].Value);
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that returns todays sessions for the given roomID
string query = @"UPDATE Attendance" +
" SET TagID= @tagNo, SessionID= @sessionNo, ScanningTime= @scantime ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("tagNo", SqlDbType.Int).Value = tagID;
command.Parameters.Add("sessionNo", SqlDbType.VarChar).Value = sessionID;
command.Parameters.Add("scantime", SqlDbType.DateTime).Value = ScanningTime;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
MyConn.Close();
}
}
当我单击按钮保存更改时,我收到一个错误:
An unhandled exception of type 'System.Data.SqlTypes.SqlTypeException' occurred in System.Data.dll
Additional information: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
编辑:
回顾我的 SSMS,尝试更新表后,出勤表的内容发生了变化。原始记录被手动添加的记录替换(尽管有错误)。
UPDATE查询执行后的考勤表:
TagID SessionID ScanningTime
int nvarchar datetime
---------------------------------------
5453453 Test1 2013-08-16 14:20:00.000