连接到数据库

时间:2011-12-01 11:56:40

标签: c# sql-server database-connection connection-string

今天早上我遇到了一个大问题。我的SQL Server昨天有一个巨大的错误,我不得不重新安装它。

在我的客户端,当我尝试登录并输入密码时,我总是收到此错误:

  

对象引用未设置为对象的实例。

     

描述:执行期间发生了未处理的异常   当前的网络请求。请查看堆栈跟踪   有关错误及其来源的更多信息   码。

     

异常详细信息:System.NullReferenceException:不是对象引用   设置为对象的实例。

     

来源错误:

    public User GetUser(string username, string password)
    {
        // Get the User

        dynamic queryStringLogon = ("SELECT Login, Id, Password, BugLogin, Guid FROM Users WHERE (Login LIKE '" + username + "') ");

        SqlCommand theCommand = new SqlCommand(queryStringLogon);

        SqlDataReader reader = GetData(theCommand);

Line 31:             User user = null; 
Line 32:  
Line 33:             if (reader.HasRows) 
Line 34:             { 
Line 35:                user = new User();

这就像我的SQL数据库中没有任何东西......这是我的连接字符串。我真的不知道它有什么问题。

<connectionStrings>
   <remove name="LocalSqlServer" />
   <add name="LocalSqlServer" 
        connectionString="data source=.\SQLEXPRESS;Initial Catalog=DataUi;Integrated Security=SSPI;User Id=clientportaluser;Password=aspen1aspen1;User Instance=true" 
        providerName="System.Data.SqlClient" />
</connectionStrings>

我还为clientportaluser设置了dataread和datawrite访问权限。

 private SqlDataReader GetData(SqlCommand command)
    {
        command.Connection = Connection;

        //using (Connection)
        //{

        try
        {

            if (Connection.State == System.Data.ConnectionState.Closed)
            {
                Connection.Open();
            }

            SqlDataReader reader = command.ExecuteReader();
            return reader;
        }
        catch (Exception e)
        {
            return null;
        }
        finally
        {
            // Connection.Close();
        }

        //}
    }

    private SqlConnection Connection
    {
        get
        {
            if (_sqlConnection == null)
            {
                _sqlConnection = new SqlConnection(_conString);
            }
            return _sqlConnection;
        }
    }

    private string _conString;

    private SqlConnection _sqlConnection;

FIXED:错误是用户实例设置为false。

3 个答案:

答案 0 :(得分:2)

为什么你同时拥有“集成安全性= SSPI”;和 “用户ID = clientportaluser;密码= aspen1aspen1;” toghether 使用一个,然后尝试。

答案 1 :(得分:1)

如果您收到错误onconnect(如果生成了异常,请发布异常),那么当您还原数据库时,您可能没有将用户帐户添加回有效用户。请检查您的用户是否有权访问数据库,并且它具有足够的权限来执行/选择您要执行的任何操作。

如果您使用的是Sql Server Management Studio,请查看安全分支。

答案 2 :(得分:1)

如果你启动SQL事件探查器是什么发送到数据库?您可以通过Management Studio访问数据库吗?