C# 用Mysql的count(*)判断是否存在,若存在就修改,不存在就插入遇到的问题

1如何获取到count(*)

Convert.ToInt32(msc.ExecuteScalar())获取到值
这里需要注意一点的是必须用Convert.ToInt32强转
否则会报 指定数据转换无效

select Count(SlotID) from items where PlayerID='{0}' and RoleIndex='{1}' and SlotID='{2}'
using (MySqlCommand msc = new MySqlCommand(sql,sqlconn))
			{
				try
				{
					if (Convert.ToInt32(msc.ExecuteScalar()) > 0)//在这获取到
					{
						msc.CommandText = string.Format("update items set ItemID='{0}',Count='{1}' where PlayerID='{2}' and RoleIndex='{3}' and SlotID='{4}' ", ItemId, count, playid, RoleIndex, SlotN);
					}
					else
					{
						msc.CommandText = string.Format("insert Into items set SlotID='{0}',ItemID='{1}',Count='{2}', PlayerID='{3}',RoleIndex='{4}'", SlotN, ItemId, count, playid, RoleIndex);
					}
					msc.ExecuteNonQuery();
					return true;
				}
				catch (Exception e)
				{
					Console.WriteLine("DataMgr:[SaveEqus]:" + e.Message);
					return false;
				}
				
			}

这时候你运行发现还是报错,会报一个

Fatal error encountered during command execution

在执行命令时遇到致命错误
记得加一个(允许使用变量)Allow User Variables=True;

string connstr = "Database=rpg;DataSource=127.0.0.1;";
			connstr += "User Id=root;Password=root;port=3306;Allow User Variables=True;";

以上是小老弟遇到的问题,若有错误请大佬们指出。

你可能感兴趣的:(C# 用Mysql的count(*)判断是否存在,若存在就修改,不存在就插入遇到的问题)