In. net, there are two ways to update a database using ado.net. One is to directly update the data source, the other is to update the data source first, and then update the data source using the data adapter update method.
First, we will introduce a simple method to directly update the data source using data commands. In actual. Net projects, this method is widely used and is suitable for directly updating data sources in the following two cases:
1. If you do not directly use SQL statements, but use stored procedures to update data;
2. Real-time data updates require the database to respond quickly to data updates.
The following code updates the data source directly using the Data command:
Dim conn as new sqlconnection
Dim cmd as new sqlcommand
Conn. connectionstring = "Server = localhost; database = pub; user id = sa; Password ="
Conn. open ()
Cmd. Connection = Conn
Cmd. commandtype = commandtype. Text
Cmd. commandtext = "delete from authors where au_lname = @ au_lname"
Cmd. Parameters. Add ("@ au_lname", textbox1.text)
'Return value is the number of affected rows.
Dim result as integer
Result = cmd. executenonquery ()
Conn. Close ()
If the stored procedure is used:
Create a stored procedure in the database: deletelname
Create proc deletelname (@ au_lname varchar (40 ))
As Delete from authors where au_lname = @ au_lname
Dim conn as new sqlconnection
Dim cmd as new sqlcommand
Conn. connectionstring = "Server = localhost; database = pub; user id = sa; Password ="
Conn. open ()
Cmd. Connection = Conn
Cmd. commandtype = commandtype. storeprocedure
Cmd. commandtext = "deletelname" 'stored procedure name
Cmd. Parameters. Add ("@ au_lname", textbox1.text) 'to pass parameters to the stored procedure, ensure that the variable names are consistent
'Return value is the number of affected rows.
Dim result as integer
Result = cmd. executenonquery ()
Conn. Close ()
If the stored procedure involved does not exist in the database, the code will give an error.