Sql参数转义

在动态构造Sql语句时,有时候参数里面可能说出现 ‘、 “ 、 \,特殊字符,直接执行就会出现问题。


        public sealed class MySqlHelper
	{
		[Obsolete("Use MySqlConnection.ClearAllPools or MySqlConnection.ClearAllPoolsAsync")]
		public static void ClearConnectionPools() => MySqlConnection.ClearAllPools();

		/// <summary>
		/// Escapes single and double quotes, and backslashes in <paramref name="value"/>.
		/// 在值中转义单引号和双引号以及反斜杠
		/// </summary>
		public static string EscapeString(string value)
		{
			if (value is null)
				throw new ArgumentNullException(nameof(value));

			StringBuilder? sb = null;
			int last = -1;
			for (int i = 0; i < value.Length; i++)
			{
				if (value[i] == '\'' || value[i] == '\"' || value[i] == '\\')
				{
					sb ??= new StringBuilder();
					sb.Append(value, last + 1, i - (last + 1));
					sb.Append('\\');
					sb.Append(value[i]);
					last = i;
				}
			}
			sb?.Append(value, last + 1, value.Length - (last + 1));

			return sb?.ToString() ?? value;
		}
	}
posted @ 2020-09-24 10:10  Herenwei_Wayne  阅读(480)  评论(0编辑  收藏  举报