读取后如何插入数据 [英] how can I insert data after read it

查看:66
本文介绍了读取后如何插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从表中读取了一些数据,然后我想要对其进行编辑,然后将编辑后的数据插入数据库中,我编写了这段代码,但是运行之后,旧数据插入了数据库中.我该怎么办?
这是我的代码;

I read some data from table and after that I want to edit it ande then insert edited data to database I write this code but after runing it,old data inserts in to data base.what should I do?
here is my code;

protected void Page_Load(object sender, EventArgs e)
 {
        SqlCommand cmd = new SqlCommand();
    cmd.Connection = new SqlConnection(Class1.CnnStr);
    SqlDataReader reader;


    cmd.CommandText = "select ChequeNo,ChequeDate from table where Number=@Number";
    cmd.Connection.Open();
    cmd.Parameters.AddWithValue("@Number", Number_lbl.Text);
    reader = cmd.ExecuteReader();

    if (reader.Read())
    {

        ChequeNo_txt.Text = reader["ChequeNo"].ToString();
        ChequeDate_txt.Text = reader["ChequeDate"].ToString();
        reader.Close();
    }
    cmd.Connection.Close();
 }

 protected void SAVE_bt_Click(object sender, EventArgs e)
 {
     SqlCommand cmd1 = new SqlCommand();
     cmd1.Connection = new SqlConnection(Class1.CnnStr);

     cmd1.Connection.Open();
     cmd1.Parameters.AddWithValue("@Number", Number_lbl.Text);
     cmd1.CommandText = "update table set ChequeNo=@ChequeNo,ChequeDate=@ChequeDate where Number=@Number";

     cmd1.Parameters.AddWithValue("@ChequeNo",ChequeNo_txt.Text);
     cmd1.Parameters.AddWithValue("@ChequeDate", ChequeDate_txt.Text);
     cmd1.ExecuteNonQuery();

 }

推荐答案

您好,
使用try catch块并添加一个断点
如果没有错误发生,请尝试使用cmd1.ExecuteScalar()而不是cmd1.ExecuteNonQuery()
Hello,
Use try catch block and add a breakpoint
If there is no error occuring, then please try cmd1.ExecuteScalar() instead of cmd1.ExecuteNonQuery()


cmd1.Parameters.AddWithValue("@ChequeNo",ChequeNo_txt.Text);上设置断点,并检查修改后的值是否首先发送给您数据库.

顺便说一句,在使用Parameters.AddWithValue创建变量之前,您应该首先验证文本框中的数据,否则对于可能只接受整数值的列,您可能最终使用varchar变量.

HTH!

如果解决了您的问题,请标记为解决方案
Have breakpoint on cmd1.Parameters.AddWithValue("@ChequeNo",ChequeNo_txt.Text); and check if the modified value is first sent to your database.

BTW, you should first validate the data from your textboxes before creating variables using Parameters.AddWithValue, else you might endup with varchar variable for a column that accepts only integer values.

HTH!

Mark as solution if it solves your problem


这篇关于读取后如何插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆