how to insert row in SQL database in ADO.Net Connection oriented mode

Deadly 提交于 2020-01-15 09:44:07

问题


I have a database in which a table has name Registration which is used to register the user.

It has only two column one is Username and one is password.

A page named Register.aspx is used for registering the member which have two textbox one is for taking Username(textbox1) and one is for taking password(textbox2) and one button for insert these value in database.

The Main problem is that we cannot write statement like this :

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

I am using ADO.net Connection oriented mode, I googled but I didn't find any way to insert row in SQL database in connected mode. Please provide me a idea for inserting this row?


回答1:


ADO.NET has DataReader which supports Connected mode. All else are disconnected.

DataReader is connected architecture since it keeps conneection open untill all records are fetched

If you want to insert in ADO.NET then you should perform the following steps:

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


    }



回答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
        {

        }

But ADO.net is useless for enterprice development. You have to have and abstraction from Data Acess Layer and go to entities, not table records Use the ORM, Luke!




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


来源:https://stackoverflow.com/questions/14090914/how-to-insert-row-in-sql-database-in-ado-net-connection-oriented-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!