【问题标题】:ConnectionStrings error c#连接字符串错误 c#
【发布时间】:2018-03-07 12:58:05
【问题描述】:
    private void button2_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "")
        {
            try
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["DeathWish"].ToString();
                con.Open();
                string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text);
                SqlCommand cmd = new SqlCommand(query,con);
                SqlDataReader dr = cmd.ExecuteReader();
                string[] s = new string[] { };
                while (dr.Read())
                {
                    s = dr["Decision"].ToString().Split(',');
                }
                int length = s.Length;
                for (int i = 0; i < length - 1; i++)
                {
                    string fetr = s[i];
                    for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
                    {
                        if (checkedListBox1.Items[j].ToString() == s[i])
                        {
                            checkedListBox1.SetItemChecked(j, true);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.ToString());
            }
        }       

string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text); 是有错误的行。 已编辑第二张图片* 我想使用复选框列表检索数据库中的特定值

这是图片:

error msg i wanted to retrieve the data on the database and show the specific value

【问题讨论】:

  • 那么,在您尝试设置连接字符串之前,con 是否已经打开?它是一个字段而不是方法变量这一事实表明其他方法可以访问它,因此请检查您是否忘记在某个地方关闭它(见鬼,您甚至没有在 button2_Click 方法中关闭它)。跨度>
  • 或者在更改连接字符串或再次打开之前检查连接是否打开。
  • 另外你应该阅读msdn.microsoft.com/en-us/library/…这将帮助你防止Sql Injections。
  • "string query = string.Format...is the line with error" - 实际上我怀疑它是 它之前的两行

标签: c#


【解决方案1】:

所以有几件事:

考虑将您的数据库访问代码包含在 using 块中,并使用您的连接字符串实例化一个新连接。这可以确保 - 无论是通过错误还是通过完成块 - 连接都被正确关闭和处理掉。

其次,如果您还在处理事务,则将 try/catch 移到 using 语句中是一种很好的做法,因为您可以在 catch 块中提交完成或回滚。

最后,从不使用字符串连接来构建您的查询,当您连接的数据源来自用户控件时(见鬼,永远不要这样做)。时至今日,SQL 注入仍然是 OWASP 软件中的第 3 大安全风险,需要加以压制。

必读:

OWASP - Top 10 Web Application Security Risks
SQL Injection - Wikipedia
SQL Injection - Technet

private void button2_Click(object sender, EventArgs e)
{
    if (textBox1.Text != "")
    {
        // a SqlConnection enclosed in a `using` statement will auto-close, and will ensure other resources are correctly disposed
        using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DeathWish"].ToString())) 
        {
            try
            {
                con.Open()
                string[] s = new string[] { };                    
                string query = "Select [ID],Decision from Data where [ID]=@id order by Decision";
               
                SqlCommand cmd = new SqlCommand(query, con);
                SqlParameter idParam = new SqlParameter();
                idParam.ParameterName = "@id";
                idParam.Value = textBox1.Text;
                cmd.Parameters.Add(idParam);

                SqlDataReader dr = cmd.ExecuteReader();
                
                while (dr.Read())
                {
                    s = dr["Decision"].ToString().Split(',');
                }
                int length = s.Length;
                for (int i = 0; i < length - 1; i++)
                {
                    string fetr = s[i];
                    for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
                    {
                        if (checkedListBox1.Items[j].ToString() == s[i])
                        {
                            checkedListBox1.SetItemChecked(j, true);
                            break;
                        }
                    }
                }
            
            }
            catch (Exception ex)
            {
            MessageBox.Show(ex.Message + ex.ToString());
            }
        }
    }
}   

【讨论】:

  • 不错。唯一的问题是如果使用 TransactionScope there is no rollback and so no need for the try-catch to be inside the using 除非您当然指的是 SqlTransaction
  • 同意,我一直这样做是为了建立肌肉记忆。基本上“您正在处理数据库,只需采用它,这样如果您忘记它就不会发现您”,但我同意在这种情况下它不相关。
【解决方案2】:

您的连接(仍然)打开,因此您必须检查它是否已关闭。如果是,您可以打开一个新连接。

所以试试这个:

private void button2_Click(object sender, EventArgs e)
{
    if (textBox1.Text != "")
    {
        try
        {
            if(con.State == ConnectionState.Closed)
            {
                 con.Open();
            }
            con.ConnectionString = ConfigurationManager.ConnectionStrings["DeathWish"].ToString();


            string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text);
            SqlCommand cmd = new SqlCommand(query,con);
            SqlDataReader dr = cmd.ExecuteReader();
            string[] s = new string[] { };
            while (dr.Read())
            {
                s = dr["Decision"].ToString().Split(',');
            }
            int length = s.Length;
            for (int i = 0; i < length - 1; i++)
            {
                string fetr = s[i];
                for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
                {
                    if (checkedListBox1.Items[j].ToString() == s[i])
                    {
                        checkedListBox1.SetItemChecked(j, true);
                        break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + ex.ToString());
        }
    }       

【讨论】:

  • 很确定这仍然会在con.ConnectionString = ...上呕吐
  • 你需要在connectionString改变之前放置if块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2011-08-17
  • 2013-02-11
  • 1970-01-01
相关资源
最近更新 更多