我有一个数据库,其中一个表的名称Registration用于注册用户。
它只有两列,一是Username和一是password。
一个名为的页面Register.aspx用于注册具有两个文本框的成员,一个用于获取Username(textbox1),一个用于获取password(textbox2),一个用于将这些值插入数据库的按钮。
主要问题是我们不能写这样的语句:
Insert into Registration (Username, password)
values ('TextBox1.text','TextBox2.text')
Run Code Online (Sandbox Code Playgroud)
我正在使用 ADO.net 面向连接的模式,我用谷歌搜索但我没有找到任何方法在连接模式下在 SQL 数据库中插入行。请给我一个插入这一行的想法?
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();
}
}
Run Code Online (Sandbox Code Playgroud)