返回首页

  try

            {

                SqlConnection con = new SqlConnection(" Data Source=AHSAN-PC\\SQLEXPRESS;Initial Catalog=bank;Integrated Security=SSPI;MultipleActiveResultSets=True;");

                con.Open();

                //MessageBox.Show("connected");

                SqlCommand cmd = new SqlCommand("select * from account",con);

                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read().Equals(textBox1.Text))

                {

                    MessageBox.Show("sorry duplicate acc no.");

                }

                else

                {

                    //SqlCommand cmd = new SqlCommand("select * from account",con);

                    cmd=new SqlCommand("insert into account values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')", con);

                    SqlDataReader drr = cmd.ExecuteReader();

                    drr.Close();

                    MessageBox.Show("data added");

                    

                    

                }

                dr.Close();

                con.Close();

                //MessageBox.Show("data added");

            }

            catch (Exception ex)

            {

                MessageBox.Show("error" + ex.Message);

}

我得到错误的,"这是一个命令,必须先关闭已打开的DataReader。"

请帮助我。我使用的是SQL Server 2005和C#

我给在代码2中的SQL查询,选择和其他insert.as我想,以防止重复帐户号记录在我的应用程序之一。

回答

评论会员:游客 时间:2012/02/04
,错误信息是不够的调试问题如果您使用的嵌套GenerateCSVReport本质,你将需要启用多个活动的记录集。数据库应该支持这一点。这里是一个imgsrc=http://www.orcode.com/img/ico/smiley_smile.gif]MARS一般激活{A}]
。digimanus:你不能使用SqlDataReader的第二个请求,而第一个请求是不喷气完成(关闭()命令)。更好地为第二个查询的第二SqlDataReader对象
评论会员:VetalRMP 时间:2012/02/04
您使用打开的DataReader,并在同一时间执行命令
在这种情况下,你可以替换下面的代码块:
{C}
:像这样的东西

var cmd = new SqlCommand("SELECT COUNT (*) FROM [account] WHERE fieldname = @fieldname",con);

cmd.Parameters.AddWithValue("@fieldname", textBox1.Text);

var isExists = Convert.ToInt32(cmd.ExecuteScalar()) > 0;

if (isExists)

这将解决问题,只需更换与db表中的字段名称"字段名",你比较的textBox1.Text。

一些小建议:
1。不要使用您的SQL查询(SQL注入问题)准备非字符串。使用参数,而不是
2。节中的应用程序配置文件存储在连接字符串;
3。可支配的资源提供更多的关注。在任何问题在try块DB连接的情况下将继续开放;
4。使用string.Format或StringBuilder字符串连接;
如果它只是测试项目或例子,然后不去管{S0的}
评论会员:游客 时间:2012/02/04
Anele.Ngqandu:扇贝做,我不是说其最好的,但我从数据库中读取的东西,比较的东西,我有笏,我想插入。例如,我会检查密码,如果我的数据库中不存在{体C3}{的C4}现在systemBusinessLayer是我的班,在那里你可以找到的方法getAuthentication(){C5的}{5233}是我的StoredProcedure的SQL查询。希望它可以帮助...