开发者

asp.net/ sql how can i save the text in Server.GetLastError() to DB when it has single quotes inside the string?

i have the below code and find that the text value represented in Server.GetLastError contains single quotes and breaks my SQL insert code.

Exception ex = Server开发者_开发技巧.GetLastError();

StringBuilder theBody = new StringBuilder();        
theBody.Append("Error Message: " + ex.ToString() + "\n");

Server.ClearError();

try
    {
        string sSQL = "INSERT INTO PMISwebErr VALUES ('" + theBody.ToString() + "', GETDATE())";

        using (System.Data.SqlClient.SqlConnection con = STAR.Global.GetConnection())
        {
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, con);
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.ExecuteScalar();
        }
    }
    catch (Exception exe) {
        Response.Redirect("~/default.aspx?Err="+ exe.Message.ToString() );
    }


    string sSQL = "INSERT INTO PMISwebErr VALUES (@errVal, GETDATE())";

    using (System.Data.SqlClient.SqlConnection con = STAR.Global.GetConnection())
    {
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, con);
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue( "@errVal", theBody.ToString() );
        cmd.ExecuteScalar();
    }

You should always use parameters in your SQL Statements. Not only does it handle cases such as strings with single-quotes, but it helps to protect you against SQL injection attacks.


Welcome to the wonderful world of SQL Injection attacks...

Option 1: search and replace theBody.ToString(), replacing "'" with "''"

Option 2: rewrite your SQL command to use parameters.

And, just because, you need to check this link too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜