简体   繁体   English

在C#中评估sql语句的最佳方法是什么?

[英]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? 在C#中评估SQL语句以确定它是否不仅仅是选择的最佳方法是什么? - 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? 我可以使用的开箱即用C#dlls / functions的任何想法,或者这是我应该使用字符串解析技术编写自己的东西?

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. 创建只具有读访问权限的数据库用户,然后,除SELECT之外的任何其他查询都将失败。

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): 一种方法是使用事务然后回滚,有明显的限制(可能不适用于复杂的查询,例如返回多个结果集以及其间的其他更新,并且不适用于使用非回滚命令(如DBCC)的查询 - 对于像这样的情况,可能想要捕获异常):

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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