How to do Commit/rollback in sql server using VB.net - asp.net

I'm working on an asp.net application which involves sql server as database. After writing huge function in vb.net, I had to select , insert and update different tables using one n other. I realized that, if all of this executed in one go then its a win win situation. If all of this doesn't go well then it would create a huge mess.
When we do DML operations in Oracle, we had to
commit;
rollback;
after every DML operation. My question is how do we do the same thing in sql server using VB.net.
My search leads to write a procedure #sql server. Inseration and delation will be done via sorted procedure. But I want it as normal operations like
SqlCommand("some query", connection")
Is it possible to do commit or rollback without using sorted procedures??
Thanks in advance!

You can also use a TransactionScope, which gives a bit cleaner code than managing transactions yourself.
Using transaction As NewTransactionScope()
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
command.ExecuteNonQuery()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
command.ExecuteNonQuery()
End Using
' If we do not run Commit(), e.g. an error occurs before we get here,
' the transaction will automatically roll back when we leave the Using block below
transaction.Commit()
End Using

You should use SqlTransaction.
Here is a shameless copy-paste from MSDN:
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
Dim transaction As SqlTransaction
' Start a local transaction
transaction = connection.BeginTransaction("SampleTransaction")
' Must assign both transaction object and connection
' to Command object for a pending local transaction.
command.Connection = connection
command.Transaction = transaction
Try
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
command.ExecuteNonQuery()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
command.ExecuteNonQuery()
' Attempt to commit the transaction.
transaction.Commit()
Console.WriteLine("Both records are written to database.")
Catch ex As Exception
Console.WriteLine("Commit Exception Type: {0}", ex.GetType())
Console.WriteLine(" Message: {0}", ex.Message)
' Attempt to roll back the transaction.
Try
transaction.Rollback()
Catch ex2 As Exception
' This catch block will handle any errors that may have occurred
' on the server that would cause the rollback to fail, such as
' a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
Console.WriteLine(" Message: {0}", ex2.Message)
End Try
End Try
End Using
End Sub

Related

Parameterizing sql in asp

I'm not terribly familiar with asp, but I have one project with a page of it.
<%
'declare the variables
Dim Connection
Dim ConnString
Dim Recordset
Dim SQL
Dim userName
userName = Request.Form("userName")
'define the connection string, specify database driver
ConnString="JJJJJ"//connection information
'declare the SQL statement that will query the database
SQL = "SELECT info AS Lunch, "
SQL = SQL & "FROM dbo.AgentActivityLog WHERE UserId = '" & userName & "'
'create an instance of the ADO connection and recordset objects
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'Open the connection to the database
Connection.Open ConnString
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection
'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'process record
Next
Recordset.MoveNext
Loop
End If
'close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
%>
How do I parameterize the username? I have no way to debug, no knowledge of how this language works, so whatever I tried failed and I have no idea why.
I would suggest you look at the Answer on following link as it will fill in the answers you seek:
VBA, ADO.Connection and query parameters
From the code provided critical missing piece is the ADODB.Command for the SQL to actually be run and to add the parameter the query you would :
Set Param = Command.CreateParameter("#userid",adVarChar,adParamInput)
Param.Value = userName
Command.Paramters.Append Param

Try Catch Exception running SQL Query Twice

This function seems to be running the SQL query twice, any idea why?
When I run an insert SQL query it inserts the data but also brings back this error:
Violation of PRIMARY KEY constraint 'PK__SD_T_Cod__143F51C51BFD2C07'.
Cannot insert duplicate key in object 'dbo.SD_T_Code'. The duplicate
key value is (t-503).
This seems to tell me that it is running the SQL twice, it gets inserted the first time, but the second time it doesn't insert because the id already exists (it got created with the first insert)
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim connStr As String = ConfigurationManager.ConnectionStrings("dbConnect").ConnectionString
Dim con As New SqlConnection(connStr)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
'resultSQL.Text = ex.Message
Return False
Finally
resultSQL.Text = "Successfully Saved"
con.Close()
con.Dispose()
End Try
End Function
End Class

how to update entry in mysql table from asp.net?

In mysql workbench, I can type
UPDATE contact_log
SET note = 'test1'
WHERE customer = 'customer'
and it will update the customer's note.
WHen i try this in asp.net, it has no effect.
Try
conn.Open()
cmd.Connection = conn
Catch ex As Exception
End Try
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
reader = cmd.ExecuteReader()
conn.Close()
conn.Dispose()
Some facts are that the connection string is correct, I can use select and bring back data with no problem, and the request.querystring("ID") brings back the customer name.
Is there a better way to update a mysql table from asp.net, or a way that actually works?
Many problems in your code.
Do not use string concatenation to build sql commands, but
parameterized query
Do not catch exceptions and swallow them
Use the appropriate using statement to close and dispose the
connection
Of course an INSERT/UPDATE/DELETE statement requires ExecuteNonQuery
To summarize I would change your code to this
Dim cmdText = "UPDATE contact_log SET note = #note WHERE customer = #cust"
Using conn = new MySqlConnection(connString)
Using cmd = new MySqlCommand(cmdText, conn)
conn.Open()
cmd.Parameters.AddWithValue("#note",TextBox2.Text)
cmd.Parameters.AddWithValue("#cust",Request.QueryString("ID"))
Dim rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Parameterized query are very important because you avoid Sql Injections and parsing problems with string containing quotes (You will get a syntax error if the TextBox2 contains a text with a single quote)
The Using Statement will ensure that youR connection is properly closed and disposed also in case of exceptions and you avoid dangerous memory leaks and get lower usage of system resources
The exception is better handled on a upper level of your code where you could show a message to your user or write in an error log. Catching an exception and doing nothing is very bad because you will never learn what is the reason of failure in your code.
You're using the wrong command... You're WRITING to the database, not reading from it - You need to change from using a reader to an execution command....
Try this:
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
cmd.ExecuteNonQuery()
conn.Close()
conn.Dispose()

database update sql not affecting database

i have this code to update a database, but when ever i run it with the right data, it executes without errors but the databse is not update
Dim conn As New SqlClient.SqlConnection(My.Resources.conn_str)
Dim SQL As String = "Update vehicle SET make=#make,reg_no=#reg_no,model=#model,year=#year,type=#type,last_service=#last_service Where (id = #id)"
conn.Open()
Try
Dim cmd As New SqlClient.SqlCommand(SQL, conn)
Try
cmd.Parameters.AddWithValue("#make", strMake)
cmd.Parameters.AddWithValue("#reg_no", strRegnNum)
cmd.Parameters.AddWithValue("#model", strModel)
cmd.Parameters.AddWithValue("#year", intYear)
cmd.Parameters.AddWithValue("#type", strType)
cmd.Parameters.AddWithValue("#last_service", LastService)
cmd.Parameters.AddWithValue("#id", ID.ToString)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
Return ex.Message
End Try
Catch ex As Exception
Return ex.Message
Finally
conn.Dispose()
End Try
can anyone help me with the reason its not working, as i don get an error message?
thanks
EDIT
i replaced the cmd.ExecuteNonQuery() with
Dim intAffected As Integer = cmd.ExecuteNonQuery()
Debug.Print(intaffected)
and i get 1 in the output window
A few thoughts:
If you have access to SQL Profiler, you can see the query, the values, the result, any triggers, any transactions, etc. This is the easiest way to identify what is going on.
If you don't have access to Profiler, update your query to include the OUTPUT clause, and return the values from inserted.* and deleted.* into a SqlDataReader using ExecuteReader. Check the results.
If the id is an int, don't use ID.ToString() on the parameter.AddWithValue. Use the integer itself, as the AddWithValue method with a string value could cause the ID parameter to be configured as a varchar/nvarchar.

sql and pooled connection error

Kindly look at the following code as this sample code gives an error when i hosted it on Hostexcellence , but locally it runs perfect, and the error is as the following:
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached
SqlDataSource1.SelectCommand = "Select Top (3) * from News Order by NewsID Desc";
SqlDataSource1.DataSourceMode = SqlDataSourceMode.DataReader;
SqlDataReader r_News = (SqlDataReader)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataGrid_News.DataSource = r_News;
r_News.Close();
DataGrid_News.DataBind();
So What's wrong with that code ??
See this: http://msdn.microsoft.com/en-us/library/s4yys16a(VS.71).aspx
Public Sub ConnectToSql()
Dim conn As New SqlClient.SqlConnection
' TODO: Modify the connection string and include any
' additional required properties for your database.
conn.ConnectionString = & _
"integrated security=SSPI;data source=SQL Server Name;" & _
"persist security info=False;initial catalog=northwind"
Try
conn.Open()
' Insert code to process data.
Catch ex As Exception
MessageBox.Show("Failed to connect to data source")
Finally
conn.Close()
End Try
End Sub
You should always include a finally clause to ensure that your connection is closed otherwise the connection will not be released (in case an exception occurs) and you will not have any more connections available.

Resources