C# 若两个字段不匹配,则在数据库表中插入新行,否则在特定列中求和值
我在数据库表中有数据: 以下是添加数据的方法:C# 若两个字段不匹配,则在数据库表中插入新行,否则在特定列中求和值,c#,sql,C#,Sql,我在数据库表中有数据: 以下是添加数据的方法: public static void AddRecordToDatatable(string WindowTitle, int TimeSpent, DateTime DateToday, string Project, string Username) { string sql = @"INSERT INTO dbo.Log (WindowTitle,TimeSpent,DateToda
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
是否匹配,如果这两个匹配,则取timespunt并将其和数据库表中现有的timespunt相加,而无需输入新行
我曾尝试在
INSERT
之后对重复键UPDATE WindowTitle=@WindowTitle,DateToday=@DateToday进行测试,但Visual Studio在调试器中为指向ON的此类命令提供了一个错误(ON附近的语法不正确)。另外,我也不确定重复上的是否是这种情况的最佳方法。您需要扩展SQL以检查您认为可能存在的记录是否存在
IF EXISTS (SELECT 1 FROM dbo.Log WHERE WindowTitle = @WindowTitle AND DateToday = @DateToday)
BEGIN
--UPDATE HERE
END
ELSE
BEGIN
-- INSERT HERE
END
或者,在调用AddRecordToDatatable
就我个人而言,我会使用诸如EF Core或NHibernate之类的ORM来执行所有这些CRUD操作。但这一切都取决于需求、限制等。在插入之前,您需要选择一种方法。如果用户名是主键,则需要使用Update而不是Insert(除非是新帐户)。