how to get connection string from app config in c#

2020-02-16 05:33发布

My app.config file:

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

Then I created DBConnection file:

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
    }

this is my login form:

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);
            }


        }

But when my project run, this error come: "Object reference not set to an instance of an object." please give me a solution. I use all suitable references

标签: c#
2条回答
▲ chillily
2楼-- · 2020-02-16 06:19

try

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

It should work

查看更多
闹够了就滚
3楼-- · 2020-02-16 06:22

Basing my answer on this solution, try:

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

Make sure you have a reference to System.Configuration as well.

Also remember to close your connection.

EDIT

Based on your new edit, try this for your code (Note I unfortunately can't test if this works due to my PC being broken).

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);
        }


    }

This will help prevent against SqlInjections as well.

查看更多
登录 后发表回答