小编典典

由于NullReferenceException而无法连接到Sql Server

sql

我有一个以“登录”表单开头的Windows窗体应用程序,当我在其余应用程序上工作时,“登录”表单过去几天都很好,因为我有两个数据库一个DB.mdf和一个MYD.sdf,所以我得到了一个错误

未处理NullReferenceException

你调用的对象是空的。

对于此特定的代码行—>

private void button1_Click(object sender, EventArgs e)
    {
        string path=@"C:\Users\Srinath\Documents\Visual Studio 2010\Projects\TESTFEE\TESTFEE\DB.mdf";
SqlConnection con =new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFilename='"+path+"';User Instance=True");

            string constring=ConfigurationManager.ConnectionStrings["ConnectionStringFMS"].ConnectionString;
         //SqlConnection con=new SqlConnection(constring);

        SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from LOGIN where USERNAME='" + textUser.Text + "' and PASSWORD='" + textPass.Text + "'", con);
        DataTable dt = new DataTable();

        try
        {
            sda.Fill(dt);
            if (dt.Rows[0][0].ToString() == "1")
            {
                this.Hide();
                e1.Show();

            }
            else
            {

                HoldButton();
                MessageBox.Show("Please Enter Your Right Credentials");
            }

        }
        catch (SqlException ex)
        {

            MessageBox.Show(ex.Message);
        }




        }//![The error i get ][1 -]

我尝试将配置文件用于连接字符串,然后再直接使用SqlConnection进行连接。我在Management Studio中使用Sql Server 2008
r2时,我首先收到无法连接到默认数据库的问题。在一个应用程序中两种不同类型的数据库,我尝试重新安装sql server 2008,但没有用,请帮助


阅读 134

收藏
2021-05-16

共1个答案

小编典典

将您的连接字符串放在webconfig中,如果您将* .mdf放在App_Data文件夹中,则使用这种格式是可行的

<connectionStrings>
  <add name="ConnectionName"
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
    providerName="System.Data.SqlClient" />
</connectionStrings>
2021-05-16