简体   繁体   English

如何从C#中的应用程序配置获取连接字符串

[英]how to get connection string from app config in c#

My app.config file: 我的app.config文件:

<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: 然后我创建了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
    }

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 我使用所有合适的参考

Basing my answer on this solution , try: 根据此解决方案我的答案,请尝试:

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

Make sure you have a reference to System.Configuration as well. 确保还具有对System.Configuration的引用。

Also remember to close your connection . 还记得关闭您的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). 根据您的新编辑,对您的代码进行尝试(请注意,由于我的PC损坏,遗憾的是我无法测试此方法是否有效)。

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. 这也将有助于防止SqlInjections

try 尝试

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

It should work 它应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用C#中的app.config文件获取连接字符串 - Get connection string using app.config file in C# 从C#中的app.config文件检索连接字符串后如何打开连接 - how to open a connection after retrieving the connection string from an app.config file in C# 如何从app.config文件中获取实际的连接字符串值,以及如何在DbContext构造函数C#中添加密码字符串 - How get an actual connection strings values from app.config file and add a password string in DbContext constructor C# C#连接字符串-从配置部分获取 - C# connection string - Get from config section 如何通过C#从App.config文件中读取连接字符串 - how to read the connection string from App.config file by C# 如何从C#中另一个应用程序的app.config / web.config文件中提取连接字符串 - How to extract connection string from another application's app.config / web.config file in C# 获取不是来自App.Config的连接字符串吗? - Get the connection string not from App.Config? 从app.config获取连接字符串 - Get connection string from app.config 从 App.config 获取连接字符串 - Get connection string from App.config app.config文件C#winforms保留连接字符串 - app.config file C# winforms preserve the connection string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM