File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
src/MySqlConnector/MySqlClient
tests/MySqlConnector.Tests Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 11using System ;
2+ using System . Text ;
23
34namespace 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments