【问题标题】:how to insert row in SQL database in ADO.Net Connection oriented mode如何在 ADO.Net 面向连接的模式下在 SQL 数据库中插入行
【发布时间】:2015-04-02 16:29:32
【问题描述】:

我有一个数据库,其中有一个名为Registration 的表,用于注册用户。

它只有两列,一是Username,一是password。

一个名为Register.aspx的页面用于注册会员,该页面有两个文本框,一个用于获取Username(textbox1),一个用于获取password(textbox2),一个按钮用于将这些值插入数据库。

主要问题是我们不能这样写语句:

Insert into Registration (Username, password) 
values ('TextBox1.text','TextBox2.text')

我正在使用 ADO.net 面向连接的模式,我用谷歌搜索但我没有找到任何方法在连接模式下在 SQL 数据库中插入行。请给我一个插入此行的想法?

【问题讨论】:

    标签: sql ado.net


    【解决方案1】:

    ADO.NET 具有支持连接模式的 DataReader。其他都断开了。

    DataReader 是连接架构,因为它保持连接打开,直到获取所有记录

    如果你想在 ADO.NET 中插入,那么你应该执行以下步骤:

    private void btnadd_Click(object sender, EventArgs e)
    {
      try
      {
       //create  object  of Connection Class..................
       SqlConnection con = new SqlConnection();
    
       // Set Connection String property of Connection object..................
      con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated           Security=True";
    
     // Open Connection..................
      con.Open();
    
     //Create object of Command Class................
     SqlCommand cmd = new SqlCommand();
    
    //set Connection Property  of  Command object.............
    cmd.Connection = con;
    //Set Command type of command object
    //1.StoredProcedure
    //2.TableDirect
    //3.Text   (By Default)
    
    cmd.CommandType = CommandType.Text;
    
    //Set Command text Property of command object.........
    
    cmd.CommandText = "Insert into Registration (Username, password) values ('@user','@pass')";
    
    //Assign values as `parameter`. It avoids `SQL Injection`
    cmd.Parameters.AddWithValue("user", TextBox1.text);
    cmd.Parameters.AddWithValue("pass", TextBox2.text);
    
     Execute command by calling following method................
      1.ExecuteNonQuery()
           This is used for insert,delete,update command...........
      2.ExecuteScalar()
           This returns a single value .........(used only for select command)
      3.ExecuteReader()
         Return one or more than one record.
    
      cmd.ExecuteNonQuery();
      con.Close();
    
    
      MessageBox.Show("Data Saved");          
      }
         catch (Exception ex)
         {
                MessageBox.Show(ex.Message);
                con.Close();
         }
    
    
        }
    

    【讨论】:

    • 对,教年轻的学徒如何泄漏资源并留下永不关闭的连接。另外,请尝试在下面展示您的部落成员的示例,如何仅在出现异常后关闭连接。
    • @ArtemG 从不关闭连接?
    • @syedmohsin 你修复了帖子,在 catch 中添加了 con.close() 并且不仅尝试询问是否制作了惊讶的大眼睛? ))) 我的评论日期 - 15.11.2013,最后编辑 - 2.04.2015。很好的尝试,但没有。
    【解决方案2】:
     try
            {
    
                using (var connection = new SqlConnection(yourConnectionString))
                {
                    string queryString = "Select id, name, age from Table where name = @name";
                    using (var command = new SqlCommand(queryString, Connection))
                    {
                        command.Parameters.AddWithValue("@name", name);
    
                        Connection.Open();
                        SqlDataReader dataReader = command.ExecuteReader();
    
                        while (dataReader.Read())
                        {
                            item = new Item(long.Parse(dataReader[0].ToString()),
                                            dataReader[1].ToString(),
                                            int.Parse(dataReader[2].ToString()));
                        }
                        dataReader.Close();
                    }
    
                }
            }
            catch (Exception ex)
            {
               // if exception will happen in constructor of SqlConnection or Command, the // resource can leak but Dispose method will never be called, couse the object was not created yet.        
    
              // Trace and handle here
                throw;
            }
            finally
            {
    
            }
    

    但是 ADO.net 对企业开发毫无用处。您必须从数据访问层进行抽象并转到实体,而不是表记录 卢克,使用 ORM!

    【讨论】:

      【解决方案3】:
      using System.Data.SqlClient;
      
      string cnstr = "server=.;database=dbname;user=username;password=password;";
      SqlConnection con = new SqlConnection(cnstr);
      SqlCommand cmd = new SqlCommand { Connection = con };
      cmd.CommandText = "Insert into Registration (Username, password) values ('@user','@pass')";
      cmd.Parameters.AddWithValue("user", TextBox1.text);
      cmd.Parameters.AddWithValue("pass", TextBox2.text);
      try
      {
          con.Open();
          cmd.ExecuteNonQuery();
      }
      catch (Exception)
      {
          //something;
      }
      finally
      {
          if (con != null)
             con.Close();
      }
      

      【讨论】:

      • 哈哈 :) 你说得对@Artem,我赶时间所以我做得很快:) 顺便说一句,我是伊朗人,不是印度人。代码更正。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      相关资源
      最近更新 更多