【发布时间】:2020-11-17 01:31:16
【问题描述】:
我在数据库表中有数据:
添加数据的方法如下:
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并将其与Database Table中现有的TimeSpent相加,而不输入新行。
我尝试在 INSERT 之后测试 ON DUPLICATE KEY UPDATE WindowTitle = @WindowTitle, DateToday = @DateToday,但 Visual Studio 在调试器中针对指向 ON 的此类命令给出错误(ON 附近的语法不正确)。我也不确定ON DUPLICATE 是否是这种情况的最佳方法。
【问题讨论】:
-
在插入之前需要一个 Select 方法。如果用户名是主键,则您需要使用更新而不是插入(除非它是新帐户)。