简体   繁体   中英

Insert SQL Statement into SQL Server column

I've inherited an application with a lot of ADO work in it, but the insert/update helper method that was written returns void. We've also been experiencing a lot of issues with data updates/inserts not actually happening. My goal is to update all of them to check rows affected and depending on the results, act accordingly, but for the time being of finding what may be causing the issue, I wanted to log SQL statements that are called against the server and the number of rows affected by the statement.

This is the statement I'm attempting:

 SqlCommand com = new SqlCommand(String.Format("'INSERT INTO
     SqlUpdateInsertHistory(Statement, AffectedRows) VALUES (''{0}'', {1});'",
     statement.Replace("'", "''"), rows), con);

but it seems to constantly break somewhere in the sql that is being passed in (some cases on single quotes, but I imagine there are other characters that could cause it as well.

Is there a safe way to prep a statement string to be inserted?

I just can't rightly propose a solution to this question without totally modifying what you're doing. You're currently wide open to SQL Injection. Even if this is a local application, practice how you want to play.

using (SqlCommand com = new SqlCommand("INSERT INTO SqlUpdateInsertHistory(Statement, AffectedRows) VALUES (@Statement, @AffectedRows)", con))
{
    com.Parameters.AddWithValue("@Statement", statement);
    com.Parameters.AddWithValue("@AffectedRows", rows);

    com.ExecuteNonQuery();
}

Have you tried SQL Server Profiler? It's already been written and logs queries, etc.

Someone else tried this and got a lot of decent answers here .

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