database update sql not affecting database - asp.net

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.

Related

Execute Scalar to Label. Subquery returned more than 1 value

So I have a label which shows the username of the user. I've used this value to return their ID which I then attach to a label. I used execute scalar to do this because I wasn't sure how else to get a single value on a label.
This works fine. I then use the ID from the label and put it in another table. I can do this twice and then the page crashes saying...
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
However I don't understand. I don't pull anything from the second table on the page. I don't know why it would affect it. I feel like I've tried everything. Taking out the line that posts the ID to the label lets the page run but I need it there.
Label2.Text = User.Identity.Name
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
sql = "SELECT SupID FROM Supervisor WHERE (Email = #Email)"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.Parameters.Add(New SqlParameter("#Email", User.Identity.Name))
Dim supid1 As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Label1.Text = supid1.ToString
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
This should return the first result for you. Also, it's a good idea to employ Using blocks for objects such as connections, commands, and readers.
Using cn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True")
cn.Open()
Using cmd = New SqlCommand("SELECT SupID FROM Supervisor WHERE Email = #Email", cn)
cmd.Parameters.AddWithValue("#Email", User.Identity.Name)
Using dr = cmd.ExecuteReader
If dr.Read Then
Label1.Text = CInt(dr("SupID"))
End If
End Using
End Using
End Using
If you are not sure there are multiple rows for same email in that table, you can change the query to following, that will work for you with executescalar.
SELECT TOP 1 SupID FROM Supervisor WHERE (Email = #Email)
Horribly sorry! But yes you were right! There was another query going on in the background that I never noticed that was affecting it all. So sorry

How to do Commit/rollback in sql server using VB.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

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

Query about Oracle Connections

I seem to be getting intermittent problems with my Oracle connection indicating something about a problem with semaphores which suggest that Oracle is somehow holding onto the connections instead of removing them after they have been used.
Here's the code and connection string I use:
Connection string: user id=user;password=password;data source=dataSource; Validate Connection=true;Min Pool Size=10;Connection Lifetime=5;Connection Timeout=60;Incr Pool Size=5;
And the code I use is this:
Dim OracleConn As New OracleConnection()
Dim DataTable As DataTable
Dim queryOracle As OracleCommand
Dim OracleDataAdapter As OracleDataAdapter
Dim connStr As String = "user id=user;password=password;data source=dataSource; Validate Connection=true;Min Pool Size=10;Connection Lifetime=5;Connection Timeout=60;Incr Pool Size=5;"
OracleConn.ConnectionString = connStr
Try
OracleConn.Open()
queryOracle = OracleConn.CreateCommand()
queryOracle.CommandText = "select * from table1"
DataTable = New DataTable()
OracleDataAdapter = New OracleDataAdapter(queryOracle)
OracleDataAdapter.Fill(DataTable)
table1.DataSource = DataTable.DefaultView
table1.DataBind()
Catch OracleEx As OracleException
Throw
Catch ex As Exception
Throw
Finally
If Not OracleConn Is Nothing And OracleConn.State = ConnectionState.Open Then
OracleConn.Close()
End If
End Try
Now my questions are:
Is this the best way of doing this?
I only "Close" my connection do I need to "Dispose" of it also?
I'm using Oracle.DataAccess.Client by the way.
Any help will be much appreciated
Try to put everything between Using.
Using oracleConn as OracleConnection = new OracleConnection()
'Your stuff goes here
End Using
the same goes for Commands.
P.S. There's is no need to catch Exception if they are just thrown again.
I suggest you to use using block (Execute Dispose in the end)
Using connection As New OracleConnection()
....
End Using
2 An application can call Close more than one time. No exception is generated.
If you called Dispose method SqlConnection object state will be reset. If you try to call any method on disposed SqlConnection object, you will receive exception.

ASP.NET - VB.NET - Updating MS_Access table

I'm trying to update a record from an Ms-Access table with VB.NET and ASP.NET. I'm getting 2 errors:
On the web page that's opened I'm getting Thread was being aborted
Web Developer 2010 gives me an error says there's an error in the
UPDATE statement
This is the code so far:
Imports System.Data.OleDb
Partial Class ChangePassword
Inherits System.Web.UI.Page
Protected Sub btnChange_Click(sender As Object, e As System.EventArgs) Handles btnChange.Click
Dim tUserID As String = Session("UserID")
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;")
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where UserID=?", conn)
Dim cmd2 = New OleDbCommand("UPDATE USER SET [Password] = '" + txtConfPass.Text + "' where UserID = '" + tUserID + "'", conn)
cmd.Parameters.AddWithValue("#UserID", tUserID)
Dim read As OleDbDataReader = cmd.ExecuteReader()
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
lblUser.Text = tUserID.ToString
lblUser.Visible = True
If read.HasRows Then
While read.Read()
If txtOldPass.Text = read.Item("Password").ToString Then
cmd2.ExecuteNonQuery()
lblPass.Visible = True
End If
End While
Else
lblPass.Text = "Invalid Password."
lblPass.Visible = True
End If
conn.Close()
lblPass.Text = tUserID.ToString
lblPass.Visible = True
Any help would be appreciated.
Thanks !
First, your cmd2 fails because USER is a reserved word. Enclose in
square brackets as you already do in the first OleDbCommand.
Second, to execute a statement like UPDATE, INSERT, DELETE you call
cmd2.ExecuteNonQuery not ExecuteReader. Don't really needed that call
after the first for cmd.
Third, in the first OleDbCommand (cmd) you use a parameter for
UserID, why in the second one you revert to string concatenation for
user and password? This opens the door to any kind of Sql Injection
Attack.
Fourth, the Using statement assure that every Disposable object
used in your code will be CLOSED thus freeing the memory used by
this commands ALSO IN CASE OF EXCEPTIONS. An example of Using
statement here
(1)
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
and then
(2)
cmd2.ExecuteNonQuery()
Remove (1) - ExecuteNonQuery should do the update.
USER is a keyword in Access, add brackets the same way you have added in the Select statement. Next time, you are faced with a similar problem, print out the statement as Access would see it and try executing it on the database directly - that will point out the errors accurately.
Please use place holders for the update statement similar to the select statement.

Resources