我在数据库表中有数据:
添加数据的方法如下:
public static void AddRecordToDatatable(string WindowTitle, int TimeSpent,
DateTime DateToday, string Project, string Username)
{
string sql = @"INSERT INTO dbo.Log (WindowTitle,TimeSpent,DateToday,Project,Username)" +
" VALUES (@WindowTitle,@TimeSpent,@DateToday,@Project,@Username)";
// Create the connection (and be sure to dispose it at the end)
using (SqlConnection cnn = new SqlConnection(DBconnectionString))
{
try
{
// Open the connection to the database.
// This is the first critical step in the process.
// If we cannot reach the db then we have connectivity problems
cnn.Open();
// Prepare the command to be executed on the db
using (SqlCommand cmd = new SqlCommand(sql, cnn))
{
// Create and set the parameters values
cmd.Parameters.Add("@WindowTitle", SqlDbType.NVarChar).Value = WindowTitle;
cmd.Parameters.Add("@TimeSpent", SqlDbType.Int).Value = TimeSpent;
cmd.Parameters.Add("@DateToday", SqlDbType.DateTime).Value = DateTime.Now.Date;
cmd.Parameters.Add("@Project", SqlDbType.NVarChar).Value = Project;
cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Username;
// Let's ask the db to execute the query
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
{
//MessageBox.Show("Row inserted");
}
else
{
// This should never really happen, but let's leave it here
//MessageBox.Show("No row inserted");
}
}
cnn.Close();
}
catch (Exception ex)
{
// We should log the error somewhere,
// for this example let's just show a message
MessageBox.Show("ERROR:" + ex.Message);
}
}
}
在将数据输入数据库表之前如何检查现有记录,并在存在某个值时对其求和?
因此,基本上检查是否 WindowTitle = WindowTitle
和 DateToday = DateToday
,如果这两者匹配,则获取 TimeSpent 并将其与数据库表中现有的 TimeSpent 相加,而无需输入新的行。
我尝试在 INSERT
之后测试 ON DUPLICATE KEY UPDATE WindowTitle = @WindowTitle, DateToday = @DateToday
但 Visual Studio 在调试器中针对此类命令给出错误指向 ON(ON 附近的语法不正确)。另外,我不确定 ON DUPLICATE
是否是这种情况的最佳方法。
最佳答案
您需要扩展 SQL 来检查您认为可能存在的记录是否存在。
IF EXISTS (SELECT 1 FROM dbo.Log WHERE WindowTitle = @WindowTitle AND DateToday = @DateToday)
BEGIN
--UPDATE HERE
END
ELSE
BEGIN
-- INSERT HERE
END
或者,您可以创建一个查询方法并在调用AddRecordToDatatable
之前先调用该方法
我个人会使用 ORM(例如 EF Core 或最好是 NHibernate)来完成所有这些 CRUD 操作。但这一切都取决于要求、限制等。
关于c# - 如果两个字段不匹配,则将新行插入数据库表,否则在特定列中求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862305/