我在我的twitch機器人中使用此代碼來計算消息並將其每分鐘保存到數據庫中。插入並更新mysql值c#
所以我現在的代碼並沒有從我的數據庫中得到我想要的值,但我無法正確更新或插入值。 insert_cmd確實執行,但數據庫中的值與我試圖插入的值不一致。 affectedRows確實會返回應該受到影響的行的正確答案。另外,當我寫出insert_cmd字符串時,它看起來不錯。
private static void update_messages()
{
try
{
MySql.Data.MySqlClient.MySqlConnection mysql_connection = new MySql.Data.MySqlClient.MySqlConnection();
mysql_connection.ConnectionString = mysql_connection_string;
mysql_connection.Open();
//build query string
string select_cmd = "SELECT * FROM taperen.messages where username in (";
foreach(CountData cd in chat_messages)
{
//Console.WriteLine(cd.username);
select_cmd += "\'" + cd.username + "\',";
}
if(select_cmd == "SELECT * FROM taperen.messages where username in (")
{
mysql_connection.Close();
return;
}
select_cmd = select_cmd.TrimEnd(select_cmd[select_cmd.Length - 1]);
select_cmd += ");";
//Console.WriteLine(select_cmd);
MySql.Data.MySqlClient.MySqlCommand myCommand = mysql_connection.CreateCommand();
myCommand.CommandText = select_cmd;
MySql.Data.MySqlClient.MySqlDataReader reader = myCommand.ExecuteReader();
string insert_cmd = "";
while (reader.Read())
{
string username = reader["username"].ToString();
int index = chat_messages.FindIndex(x => x.username.Equals(username));
int current_online_count = chat_messages[index].online_count;
int current_offline_count = chat_messages[index].offline_count;
int db_online_count = (int)reader["online_count"];
int db_offline_count = (int)reader["offline_count"];
int new_online_count = current_online_count + db_online_count;
int new_offline_count = current_offline_count + db_offline_count;
insert_cmd += $"UPDATE `taperen`.`messages` SET `online_count`='{new_online_count}', `online_count`='{new_offline_count}' WHERE `id`='{reader["id"]}';";
chat_messages.RemoveAt(index);
//Console.WriteLine(username);
}
reader.Close();
mysql_connection.Close();
foreach(CountData cd in chat_messages)
{
insert_cmd += $"INSERT INTO `taperen`.`messages` (`username`, `online_count`, `offline_count`) VALUES ('{cd.username}', '{cd.online_count}', '{cd.offline_count}');";
}
mysql_connection.Open();
//Console.WriteLine(insert_cmd);
myCommand.CommandText = insert_cmd;
int affectedRows = myCommand.ExecuteNonQuery();
Console.WriteLine(affectedRows);
myCommand.Dispose();
mysql_connection.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex.Message);
}
}
的CountData類看起來是這樣的:
public class CountData
{
public string username { get; set; }
public int online_count { get; set; }
public int offline_count { get; set; }
}
數據庫看起來是這樣的:
另外,如果我做別的事情愚蠢的在我的代碼我很感激,如果你能想出一些提示:)
生成的insert_cmd看起來像什麼? – Jonny