Skip to content

Commit 9edc605

Browse files
committed
Add MySqlHelper.EscapeString. Fixes #277.
1 parent 7761106 commit 9edc605

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,40 @@
11
using System;
2+
using System.Text;
23

34
namespace MySql.Data.MySqlClient
45
{
56
public sealed class MySqlHelper
67
{
78
[Obsolete("Use MySqlConnection.ClearAllPools or MySqlConnection.ClearAllPoolsAsync")]
89
public static void ClearConnectionPools() => MySqlConnection.ClearAllPools();
10+
11+
/// <summary>
12+
/// Escapes single and double quotes, and backslashes in <paramref name="input"/>.
13+
/// </summary>
14+
public static string EscapeString(string value)
15+
{
16+
if (value == null)
17+
throw new ArgumentNullException(nameof(value));
18+
19+
StringBuilder sb = null;
20+
int last = -1;
21+
for (int i = 0; i < value.Length; i++)
22+
{
23+
if (value[i] == '\'' || value[i] == '\"' || value[i] == '\\')
24+
{
25+
if (sb == null)
26+
sb = new StringBuilder();
27+
if (i > last - 1)
28+
sb.Append(value, last + 1, i - last - 1);
29+
sb.Append('\\');
30+
sb.Append(value[i]);
31+
last = i;
32+
}
33+
}
34+
if (sb != null && last < value.Length - 1)
35+
sb.Append(value, last + 1, value.Length - last - 1);
36+
37+
return sb?.ToString() ?? value;
38+
}
939
}
1040
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using MySql.Data.MySqlClient;
2+
using Xunit;
3+
4+
namespace MySql.Data.Tests
5+
{
6+
public class MySqlHelperTests
7+
{
8+
[Theory]
9+
[InlineData("", "")]
10+
[InlineData("test", "test")]
11+
[InlineData("\"", "\\\"")]
12+
[InlineData("'", "\\'")]
13+
[InlineData("\\", "\\\\")]
14+
[InlineData(@"'begin", @"\'begin")]
15+
[InlineData(@"end'", @"end\'")]
16+
[InlineData(@"mid'dle", @"mid\'dle")]
17+
[InlineData(@"'a'b'", @"\'a\'b\'")]
18+
public void EscapeString(string input, string expected)
19+
{
20+
var actual = MySqlHelper.EscapeString(input);
21+
Assert.Equal(expected, actual);
22+
if (expected == input)
23+
Assert.Same(input, actual);
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)