具有sysadmin角色的SQL用户无法登录数据库

时间:2015-01-30 20:31:06

标签: c# asp.net sql-server

我有一个域用户帐户,用于运行特定的ASP.NET Web应用程序,它是NETOPS \ websvr。此域帐户在相关SQL Server中设置,并且具有sysadmin角色。但是,我随机收到错误,说明用户登录失败。有时它位于此数据库上,而其他数据库位于同一服务器上的不同数据库中。

我一直在网上搜索过去几个小时试图找到答案,我没有比我开始时更接近答案所以我想我会问这里是否有任何想法。下面是我的Stackexchange.Exceptional

实例的输出
Exceptions Log: WebSync
Cannot open database "alsmi" requested by the login. The login failed. Login failed for user 'NETOPS\websvr'.
System.Data.SqlClient.SqlException
System.Data.SqlClient.SqlException (0x80131904): Cannot open database "alsmi" requested by the login. The login failed.
Login failed for user 'NETOPS\websvr'.
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteScalar(String connectionString, CommandType commandType, String commandText, SqlParameter[] commandParameters)
   at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteScalar(String connectionString, CommandType commandType, String commandText)
   at GetPatchLevel.ProcessRequest(HttpContext context)
ClientConnectionId:e33983c0-da22-4050-a894-55274b46f645

Full Trace:

ProcessRequest at offset 424 in file:line:column :0:0
System.Web.HttpApplication.IExecutionStep.Execute at offset 342 in file:line:column :0:0
ExecuteStep at offset 70 in file:line:column :0:0
ResumeSteps at offset 1085 in file:line:column :0:0
BeginProcessRequestNotification at offset 96 in file:line:column :0:0
ProcessRequestNotificationPrivate at offset 187 in file:line:column :0:0
ProcessRequestNotificationHelper at offset 727 in file:line:column :0:0
ProcessRequestNotification at offset 31 in file:line:column :0:0
MgdIndicateCompletion at offset 0 in file:line:column :0:0
ProcessRequestNotificationHelper at offset 1110 in file:line:column :0:0
ProcessRequestNotification at offset 31 in file:line:column :0:0


occurred 2 hours ago on web1 (delete)
Server Variables
CONTENT_LENGTH  0
HTTP_X_FORWARDED_FOR    0.0.0.0
HTTP_X_SSL_CIPHER   AES128-SHA SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA
LOCAL_ADDR  192.168.1.117
REMOTE_ADDR 192.168.1.216
REMOTE_HOST 192.168.1.216
REQUEST_METHOD  GET
URL /Services/GetPatchLevel.ashx
URL and Query   http://website.net/Services/GetPatchLevel.ashx?dbname=alsmi&username=0000&pwd=0000&clientid=0000

Custom
SQL-Server  sqlserver1
SQL-ErrorNumber 4060
SQL-LineNumber  65536

QueryString
clientid    0000
dbname  alsmi
pwd 0000
username    0000

RequestHeaders
Host    website.net
X-Forwarded-For 0.0.0.0
X-SSL-cipher    AES128-SHA SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA
Exceptional 1.0.0.111
SQL Error Store
Server time is 1/30/2015 5:50:04 PM

以下是为数据库生成连接字符串的代码。

   public static string GetConnString(string DBName)
{
    string retval = "";
    WebSyncDatabase db = WebSyncDatabase.GetDatabase(DBName);
    SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
    csb.DataSource = db.DBServer;
    csb.InitialCatalog = db.DBName;
    csb.IntegratedSecurity = true;
    csb.ConnectTimeout = 25;
    csb.MaxPoolSize = 150;
    retval = csb.ConnectionString;
    return retval;
}

这是数据访问代码。 SqlHelper.ExecuteScalar来自Microsoft数据访问应用程序块for .NET代码未经修改。他下面的代码实际上每天为我们工作数千万次,随机例外。

 string connString = WebSyncUtils.GetConnString(dbName);
        switch (context.Request.HttpMethod.ToUpper())
        {
            case "GET":
                int retval = 0;
                try
                {
                    retval = (int)SqlHelper.ExecuteScalar(connString, CommandType.Text, "SELECT PatchLevel FROM PatchStatus");
                }
                catch (Exception ex)
                {
                    WebSyncUtils.LogMessage(string.Format("Get Next Patch Level for {0} {1} {2}", dbName, userName, pwd), ex);
                }
                context.Response.Write(retval);
                break;
            case "POST":
                break;
            default:
                break;
        }

Methodman

的更多代码示例
  /// <summary>
    /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in 
    /// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
    /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
    /// </summary>
    /// <remarks>
    /// This method provides no access to output parameters or the stored procedure's return value parameter.
    /// 
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
    /// </remarks>
    /// <param name="connectionString">A valid connection string for a SqlConnection</param>
    /// <param name="spName">The name of the stored procedure</param>
    /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
    {
        if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
        if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

        // If we receive parameter values, we need to figure out where they go
        if ((parameterValues != null) && (parameterValues.Length > 0)) 
        {
            // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
            SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

            // Assign the provided values to these parameters based on parameter order
            AssignParameterValues(commandParameters, parameterValues);

            // Call the overload that takes an array of SqlParameters
            return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
        }
        else 
        {
            // Otherwise we can just call the SP without params
            return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
        }
    }

    /// <summary>
    /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection. 
    /// </summary>
    /// <remarks>
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
    /// </remarks>
    /// <param name="connection">A valid SqlConnection</param>
    /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
    {
        // Pass through the call providing null for the set of SqlParameters
        return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
    }

    /// <summary>
    /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
    /// using the provided parameters.
    /// </summary>
    /// <remarks>
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connection">A valid SqlConnection</param>
    /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
        if( connection == null ) throw new ArgumentNullException( "connection" );

        // Create a command and prepare it for execution
        SqlCommand cmd = new SqlCommand();

        bool mustCloseConnection = false;
        PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );

        // Execute the command & return the results
        object retval;

        try
        {
            retval = cmd.ExecuteScalar();
        }
        finally
        {
            // Detach the SqlParameters from the command object, so they can be used again
            cmd.Parameters.Clear();

            if (mustCloseConnection)
                connection.Close();
        }           

        return retval;
    }

    /// <summary>
    /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
    /// using the provided parameter values.  This method will query the database to discover the parameters for the 
    /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
    /// </summary>
    /// <remarks>
    /// This method provides no access to output parameters or the stored procedure's return value parameter.
    /// 
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
    /// </remarks>
    /// <param name="connection">A valid SqlConnection</param>
    /// <param name="spName">The name of the stored procedure</param>
    /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
    {
        if( connection == null ) throw new ArgumentNullException( "connection" );
        if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

        // If we receive parameter values, we need to figure out where they go
        if ((parameterValues != null) && (parameterValues.Length > 0)) 
        {
            // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
            SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);

            // Assign the provided values to these parameters based on parameter order
            AssignParameterValues(commandParameters, parameterValues);

            // Call the overload that takes an array of SqlParameters
            return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
        }
        else 
        {
            // Otherwise we can just call the SP without params
            return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
        }
    }

    /// <summary>
    /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction. 
    /// </summary>
    /// <remarks>
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
    /// </remarks>
    /// <param name="transaction">A valid SqlTransaction</param>
    /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
    {
        // Pass through the call providing null for the set of SqlParameters
        return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
    }

    /// <summary>
    /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
    /// using the provided parameters.
    /// </summary>
    /// <remarks>
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="transaction">A valid SqlTransaction</param>
    /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
        if( transaction == null ) throw new ArgumentNullException( "transaction" );
        if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );

        // Create a command and prepare it for execution
        SqlCommand cmd = new SqlCommand();
        bool mustCloseConnection = false;
        PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );

        // Execute the command & return the results
        object retval = cmd.ExecuteScalar();

        // Detach the SqlParameters from the command object, so they can be used again
        cmd.Parameters.Clear();
        return retval;
    }

    /// <summary>
    /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified
    /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
    /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
    /// </summary>
    /// <remarks>
    /// This method provides no access to output parameters or the stored procedure's return value parameter.
    /// 
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
    /// </remarks>
    /// <param name="transaction">A valid SqlTransaction</param>
    /// <param name="spName">The name of the stored procedure</param>
    /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
    {
        if( transaction == null ) throw new ArgumentNullException( "transaction" );
        if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
        if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

        // If we receive parameter values, we need to figure out where they go
        if ((parameterValues != null) && (parameterValues.Length > 0)) 
        {
            // PPull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
            SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

            // Assign the provided values to these parameters based on parameter order
            AssignParameterValues(commandParameters, parameterValues);

            // Call the overload that takes an array of SqlParameters
            return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
        }
        else 
        {
            // Otherwise we can just call the SP without params
            return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
        }
    }


/// <summary>
    /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string 
    /// using the provided parameters.
    /// </summary>
    /// <remarks>
    /// e.g.:  
    ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
    /// </remarks>
    /// <param name="connectionString">A valid connection string for a SqlConnection</param>
    /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
    /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
        if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
        // Create & open a SqlConnection, and dispose of it after we are done
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Call the overload that takes a connection in place of the connection string
            return ExecuteScalar(connection, commandType, commandText, commandParameters);
        }
    }

1 个答案:

答案 0 :(得分:0)

从错误日志中,我看到您无法打开数据库。由于您没有共享代码,这几乎是我们目前唯一能够处理的问题 - 所以让我们专注于此。


无法打开数据库可能是由少数原因造成的,最常见的原因是:

  • 你没有预先提交
  • 数据库已被其他来源锁定
  • 数据库未明确指定。

权限

数据库最终是由系统处理的文件。因此,为了编辑它们,您需要所需的凭证 - 这可能取决于许多事情。例如,在Windows NT系统上保存在用户上的文件可能只能为该用户和其他一些用户访问;另一个很好的例子是,如果您尝试从需要管理员的CMD执行命令。

<强>解决方案: 以管理员身份运行走着瞧吧。解决了你的问题?在配置文件中需要管理员访问权限,问题就解决了。

数据库已锁定

数据库系统有很多shananigans。让我们以Microsoft Access为例 - 这是一个很棒的系统,但是新用户在了解如何使用它修复错误之前需要花费一些时间。原因很简单 - Access对它的对象非常自负。它们的名称,线程,常量和方法必须以非常特定的方式发生,否则系统会抛出一个异常和一个消息框,在visual studio中通常会导致一个未详细说明的异常。在您的情况下,数据库系统可能类似 - 由于许多原因,它可能目前已被锁定。

解决方案:保存后关闭数据库应用程序(如果已打开)。手动删除相关的进程,如果上述方法均无效,请重新启动计算机。

数据库规范

这个错误实际上与上一个错误非常相似,但这里的源不是数据库应用程序,而是操作系统本身。这可能是错误的文件名,数据库类型等的结果,解决方案是深入研究您的代码(随意分享它,我们可以帮助您)并寻找糟糕的铸件,连接,路径和所有这些。

解决方案:正如我所提到的,只需深入了解代码即可。如有必要,请重写连接部分。

编辑:关于错误,我只是注意到你得到了SQL 4060.这实际上非常适合你的描述 - 从不同的工作区执行它可能会让你得到不同的预设。试试我在“Premissions”段落中提到的解决方案,让我们知道它是如何进行的。

相关问题