如何从c#中的app config获取连接字符串

时间:2015-01-05 04:02:21

标签: c#

我的app.config文件:

<configuration>
    <connectionStrings>
        <add name="MegaPixelBizConn"
            connectionString="Data Source=PSHERATH-PC;Initial Catalog=MegaPixelBiz;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

然后我创建了DBConnection文件:

class DBConnection
    {
        #region Database connection method
        public SqlConnection Connect()
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString();

            try
            {
                conn.Open();
            }
            catch
            {
            }
            return conn;
        }
        #endregion
    }

这是我的登录表单:

SqlCommand cmd;
        DataSet ds = new DataSet();
        DBConnection db = new DBConnection();

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserName.Text == "" || txtPassword.Text == "")
                {
                    lblError.Visible = true;
                    lblError.Text = "*Enter UserName and Password";
                    //MessageBox.Show(" Enter UserName and Password .");
                    return;
                }
                else
                {
                    string sql = "SELECT * FROM login_info WHERE userName = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'";
                    cmd = new SqlCommand(sql, db.Connect());
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds);
                    int i = ds.Tables[0].Rows.Count;
                    if (i == 1)
                    {
                        this.Hide();
                        Home hm = new Home();
                        hm.Show();
                        ds.Clear();

                    }
                    else
                    {
                        lblError.Text = "*Not Registered User or Invalid Name/Password";
                        //MessageBox.Show("Not Registered User or Invalid Name/Password");
                        txtPassword.Text = "";
                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

但是当我的项目运行时,会出现以下错误: “你调用的对象是空的。” 请给我一个解决方案。我使用所有合适的参考文献

2 个答案:

答案 0 :(得分:3)

根据我this solution的答案,尝试:

conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString;

确保您也引用System.Configuration

还要记得关闭connection

修改

根据您的新编辑,请尝试使用此代码(请注意,由于我的电脑坏了,我无法测试是否有效)。

private void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtUserName.Text == "" || txtPassword.Text == "")
            {
                lblError.Visible = true;
                lblError.Text = "*Enter UserName and Password";
                //MessageBox.Show(" Enter UserName and Password .");
                return;
            }
            else
            {

                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString))
                {

                    con.Open();

                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM login_info WHERE userName = @Username AND password = @Password", con))
                    {
                        // If these two lines don't work, replace "Username" and "Password" with "@Username"/"@Password"
                        cmd.Parameters.Add(new SqlParameter("Username", txtUserName.Text);
                        cmd.Parameters.Add(new SqlParameter("Password", txtPassword.Text);
                        SqlDataReader r = cmd.ExecuteReader();
                        if(r.HasRows())
                        {
                            // this assumes that there is only one user/password and no two users with same UID and PWORD
                            this.Hide();
                            Home hm = new Home();
                            hm.Show();
                        }

                        else
                        {
                            lblError.Text = "*Not Registered User or Invalid Name/Password";
                            //MessageBox.Show("Not Registered User or Invalid Name/Password");
                            txtPassword.Text = "";
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

这有助于防止SqlInjections

答案 1 :(得分:1)

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);

应该有效