简体   繁体   中英

Escaping special characters in MySQL

Firstly I know that I should be using stored procedures by now and am getting around to it, but I need a quick fix for one of my internal only apps.

Theres a form where we can enter some text, which is appended to a HTML email, formatted all nice and then sent off to joe customer before being recorded in the mysql DB.

The problem is that whenever a user uses an apostrophe ('), the recording to the db bit fails.

I tried to get around it by having an escaping function which simply replaced ' with /' but still my mysql errors persist.

My escape function was as so..

Public Function escapechars(ByVal input As String) As String

    input = input.Replace("\", "\\")
    input = input.Replace("%", "\%")
    input = input.Replace("'", "\'")
    input = input.Replace("", " \_")

    Return input

End Function

My function for saving to the db is like so... (Bear in mind i was doing 'escapechars' prior to building db_newvalues)

 Public Function writesql(ByVal db_table As String, ByVal db_columns As String, ByVal db_newvalues As String)
    Control.CheckForIllegalCrossThreadCalls = False
    Try
        Dim cn As New MySqlConnection
        cn.Close()
        Dim timestamp As String = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        Dim myCommand As New MySqlCommand
        Dim myAdapter As New MySqlDataAdapter
        Dim SQL As String
        cn.ConnectionString = orca_connection_string
        myCommand.Connection = cn
        cn.Open()
        myAdapter.SelectCommand = myCommand
        SQL = ("INSERT INTO " & db_table & "(" & db_columns & ") VALUES (" & db_newvalues & "); SELECT LAST_INSERT_ID()")
        myCommand.CommandText = SQL
        Dim newentryid As Integer = myCommand.ExecuteScalar()
        cn.Close()
        Return newentryid
    Catch ex As Exception
        ErrorHandling(ex.ToString)
        Return "Error"
    End Try

End Function

Any help appriciated! thanks in advance!

In a string literal in a MySQL statement, the backslash character and the single quote character can be escaped by preceding with a backslash character. For example:

 SELECT 'here\'s a \\ backslash'

If single quotes are used to enclose a string literal, then a single quote within the literal can be encoded as two single quotes. For example.

 SELECT 'it''s fine like this too'

MySQL extends the ANSI SQL standard and allows double quotes to be used to enclose string literals, as long as sql_mode is not set to include ANSI_QUOTES. If we are enclosing string literals in double quotes, then double quotes within the literal will need to be escaped.


In a SQL string literal, there's no need to escape the underscore or percent characters. (It's only within the context of a LIKE comparison that the % and _ characters are wildcards; we only need to escape those if we are looking to do a match to those characters, to "escape" the character from being recognized as a wildcard.)

For debugging issues with dynamically generated this, consider logging the contents of the SQL string, and then test that SQL in another client.


NOTE: The writesql function appears to be vulnerable to SQL Injection. Preventing SQL Injection will need to be the responsibility of every function that calls writesql .

The preferred pattern for mitigating SQL Injection vulnerabilities is to use prepared statements with bind placeholders . (In VB.NET, that would be a Command object with parameters.)

https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM