如何在ADO.Net面向连接模式下在SQL数据库中插入行

时间:2012-12-30 13:01:09

标签: sql ado.net

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

它只有两个第一列Username,一个是password

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

主要问题是我们不能写这样的声明:

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

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

3 个答案:

答案 0 :(得分:4)

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();
     }


    }

答案 1 :(得分:0)

 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对于enterprice开发毫无用处。您必须拥有和抽象数据访问层并转到实体,而不是表记录 使用ORM,Luke!

答案 2 :(得分:-1)

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();
}