您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

检查数据库是否存在MSSQL C#

检查数据库是否存在MSSQL C#

注意代码上的注释,它们解释了我所做的更改。

// No point of passing a bool if all you do is return it… private bool CheckDatabase(string databaseName) { // You kNow it’s a string, use var var connString = “Server=localhost\sqlEXPRESS;Integrated Security=SSPI;database=master”; // Note: It’s better to take the connection string from the config file.

var cmdText = "select count(*) from master.dbo.sysdatabases where name=@database";

using (var sqlConnection = new sqlConnection(connString))
{
    using (var sqlCmd = new sqlCommand(cmdText, sqlConnection))
    {
        // Use parameters to protect against sql Injection
        sqlCmd.Parameters.Add("@database", System.Data.sqlDbType.NVarChar).Value = databaseName;

        // Open the connection as late as possible
        sqlConnection.open();
        // count(*) will always return an int, so it's safe to use Convert.ToInt32
        return Convert.ToInt32( sqlCmd.ExecuteScalar()) == 1;
    }
}

}

SQLServer 2022/1/1 18:53:28 有389人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶