简体   繁体   中英

What is the best way to evaluate a sql statement in C#?

What is the best way to evaluate a SQL statement in C# to determine if it does more than just select? - Ie- check if values would be changed (insert, update, delete, modify, or drop) if the statement was later executed.

Any ideas as far as out of the box C# dlls/functions i can use, or is this something I should code myself using string-parsing techniques?

Thanks.

I would use db permissions. Create a database user with read-access only and then, any queries that do anything other than SELECT will fail.

One method would be to use a transaction and then rollback, with obvious limitations (may not work on complex queries, like ones returning multiple result sets with other updates in between, and will not work on queries that use non-rollback commands like DBCC - may want to catch exceptions as well for situations like those):

using(SqlConnection sqlConn = new sqlConnection(CONNECTION_STRING))
{
    sqlConn.Open();
    using (SqlTransaction trans = sqlConn.BeginTransaction())
    {
        // execute code and see if rows are affected here
        var query = " ... " ;
        var cmd = new SqlCommand(query, sqlConn);
        var rowsAffected = cmd.ExecuteNonQuery();
        if (rowsAffected > 0) { ... }

        // roll back the transaction
        trans.RollBack();
    }
    sqlConn.Close();
}

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