【问题标题】:how to get connection string from app config in c#如何在c#中从应用程序配置中获取连接字符串
【发布时间】:2015-03-02 14:51:51
【问题描述】:

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


        }

但是当我的项目运行时,这个错误来了: “你调用的对象是空的。” 请给我一个解决方案。我使用所有合适的参考资料

【问题讨论】:

  • 调试时能否读取连接字符串?
  • 你的错误发生在conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString();这一行吗?
  • 是的,错误发生在conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString();线上
  • 您使用的是什么 DBMS?
  • 好吧,我试试我最新的编辑,看看它是否能解决你的问题(我的主电脑坏了,我的笔记本电脑上有 Ubuntu,所以没有打扰测试)。

标签: c#


【解决方案1】:

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

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

确保您也有对 System.Configuration 的引用。

还记得关闭你的connection

编辑

根据您的新编辑,为您的代码尝试此方法(请注意,由于我的 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);
        }


    }

这也有助于防止SqlInjections

【讨论】:

  • 你应该建议它是重复的......而且假设 ConfigurationManager.ConnectionStrings["MegaPixelBizConn"] 为空......也不太可能帮助 OP......
  • 您说它是重复的是正确的。鉴于提供的 Xml,我们可以说这是 null 吗?
  • 我有 System.Configuration 参考。以及我使用此代码conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString;,但错误即将到来。
【解决方案2】:

试试

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

它应该可以工作

【讨论】:

  • 提示:如果在配置文件中未找到请求的值,则将用于检索应用程序设置和连接字符串的代码包装起来会非常有帮助。与追逐另一个 NullReferenceException 相比,显示 Connection string "SecretDB" not found in configuration. 的异常可以节省实时时间。
猜你喜欢
  • 2012-01-26
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 2016-01-05
  • 2020-05-01
  • 1970-01-01
相关资源
最近更新 更多