strange workflow in ado.net with vb.net - vb.net

i had assigned a job for insert,update, delete operation in a table for my student. he had done this assignment fine. but his code is made me crazy that he wrote update code like below
Working sample:
Public Function Toeditdetails(ByVal item As Boolean)
If item = True Then
Dim con As SqlConnection
'Dim retval As Integer
con = New SqlConnection(conn)
con.Open()
Dim cmd As SqlCommand
cmd = New SqlCommand("updatelogin", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("#username", SqlDbType.VarChar, 100)).Value() = TextBox1.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#user_password", SqlDbType.VarChar, 30)).Value() = TextBox2.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#nameofuser", SqlDbType.VarChar, 100)).Value() = TextBox3.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#contact_no", SqlDbType.VarChar, 10)).Value() = TextBox4.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#email", SqlDbType.VarChar, 100)).Value() = TextBox5.Text.Trim()
cmd.Parameters.Add(New SqlParameter("#joiningdate", SqlDbType.Date)).Value() = DateTimePicker1.Value
cmd.Parameters.Add(New SqlParameter("#usergroup_id", SqlDbType.Int)).Value() = SelectedID(ComboBox1.Text)
If item = True Then
cmd.Parameters.Add(New SqlParameter("#id", SqlDbType.Int)).Value() = Label9.Text.Trim()
End If
Dim da As SqlDataAdapter
da = New SqlDataAdapter(cmd)
Dim dst As New DataSet
da.Fill(dst)
If dst.Tables.Count > 0 Then
DataGridView1.DataSource = dst.Tables(0)
End If
If Not cmd Is Nothing Then
cmd.Dispose()
End If
End If
End Function
Note there is no ExecuteNonQuery() method for his SqlCommand object and he didn't call this method in entire project. when i call function result still updating... how its happen? anyone genius can you explain whats going on above statement? any help would be appreciated
Regards and thanks
Sarva

when you call Toeditdetails method it will execute stored procedure called updatelogin
check the stored procedure and you may able to find why you receive updated result. Stored procedure several statements like below
update table1 set username ='test1' where uid =#uid;
select * from table1;
when you call stored procedure with above code you will get the table1 data but update statement will update data before you receive it.

Related

SQL Error Regarding apostrophe from datagridview using parameter in query

Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with

Call Oracle function in package in vb.net

I just begin with Oracle. I read lot of post and ... I don't find where is my mistake
I've a function in package PKG_GETOBJ
FUNCTION GetNewID(sReference IN VARCHAR2) RETURN NUMBER
IS
NewCtpVal NUMBER;
BEGIN
UPDATE TABLE set VALUE = (VALUE + 1) WHERE Field= sReference RETURN VALUE INTO NewCtpVal;
return NewCtpVal;
END;
and here how I try to call it:
Dim con As OracleConnection = GetConnexion()
con.Open()
Dim cmd As New OracleCommand With {.Connection = con}
'PKG_GETOBJ.GETNEWID('ID_OBJECT');'Sample calling in SQL with success
cmd.Parameters.Add(New OracleParameter With {.ParameterName = "sReference", .OracleDbType = OracleDbType.Varchar2, .Value = "ID_OBJECT", .Direction = ParameterDirection.Input})
cmd.Parameters.Add(New OracleParameter With {.ParameterName = "NewCtpVal", .OracleDbType = OracleDbType.Double, .Direction = ParameterDirection.ReturnValue})
cmd.CommandText = "PKG_GETOBJ.GETNEWID"
cmd.CommandType = CommandType.StoredProcedure
cmd.ExecuteNonQuery()
For Each p As OracleParameter In cmd.Parameters
HelperJournal.WriteEntry("PKG_GETOBJ " & p.ParameterName, If(p.Value Is Nothing, "null", p.Value.ToString))'Write in file
Next
con.Close()
con.Dispose()
My problem is NewCtpVal is empty, then I Database I've a number value...
Finnally I found a way...
Public Function GetNewId() As Decimal
Dim retval
Using con As OracleConnection = GetConnexion(),
cmd As New OracleCommand With {.Connection = con}
cmd.CommandText = "PKG_GETOBJ.GETNEWID"
cmd.CommandType = CommandType.StoredProcedure
Dim prm = New OracleParameter("returnvalue", OracleDbType.Decimal)
prm.Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add(prm)
Dim prm1 = New OracleParameter("sReference", OracleDbType.Varchar2)
prm1.Direction = ParameterDirection.Input
prm1.Value = "ID_OBJECT"
cmd.Parameters.Add(prm1)
con.Open()
cmd.ExecuteNonQuery()
retval = cmd.Parameters("returnvalue").Value.ToString
End Using
Return retval
End Function

Is filling a DataTable necessary for just setting variables with 2 column values?

I am trying to improve performance of an application, I have a case where a common SPROC is being used but is it necessary to fill a DataTable just to set 2 variable values?
Is there anything more efficient?
Dim Conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim CmdUsers As SqlCommand = New SqlCommand("uspGetUsers", Conn)
CmdUsers.CommandType = CommandType.StoredProcedure
CmdUsers.Parameters.Add(New SqlParameter("#UserName", Session("UserID")))
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim dtUserInfo As DataTable = New DataTable
da = New SqlDataAdapter(CmdUsers)
da.Fill(dtUserInfo)
isParent = dtUserInfo.Rows(0)("IsAdmin")
UserVal = dtUserInfo.Rows(0)("UserVal")
A SqlDataReader is the fastest way to read data from a query. Try the following:
Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
conn.Open()
Using cmd As New SqlCommand("uspGetUsers", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#UserName", Session("UserID"))
Using reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
isParent = reader("IsAdmin")
UserVal = reader("UserVal")
End While
End Using
End Using
End Using
You may need to parse the data to the correct types.
Also, note the use of Using to automatically dispose of the connection, command and reader objects: http://msdn.microsoft.com/en-GB/library/htd05whh.aspx

How to update data in MS Access Database

just want to ask if what is the proper way on updating data in ms access Database, because when I use this code, my data is not updated and it doesn't show any error, so the returned value of the function is FALSE.
below is my code.
dim conn as new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\myDb.accdb;Persist Security Info=False;")
Protected Function UpdateProduct(ByVal productDetails As ProductModel) As Boolean
reopenConnection()
cmd = New OleDbCommand("UPDATE Product Set ProductName=#prodName, Price=#price, ProductDescription=#prodDesc, CategoryId=#catId where ProductId=#prodId;", conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#prodId", OleDbType.VarChar).Value = productDetails.NewProductId
cmd.Parameters.Add("#prodName", OleDbType.VarChar).Value = productDetails.ProductName
cmd.Parameters.Add("#price", OleDbType.Decimal).Value = productDetails.Price
cmd.Parameters.Add("#prodDesc", OleDbType.VarChar).Value = productDetails.ProductDescription
cmd.Parameters.Add("#categoryId", OleDbType.Integer).Value = productDetails.CategoryId
Return cmd.ExecuteNonQuery() > 0
End Function
Private Sub reopenConnection()
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
End Sub
Thanks
My experience with access is you have to commit the transactions or you never see the update in the database. See this stackoverflow thread for the syntax.
How to implement transaction way in vb.net?

Problems calling a Stored Procedure from VB.NET

As you can probably very soon see, I am a complete newbie at VB.NET, and I am having some trouble getting output from a stored procedure in SQL Server 2005.
This is the code I use
Dim con As New SqlConnection
Dim cmd As New SqlCommand("esp_getDates", con)
Dim par As New SqlParameter("#PlaceID", SqlDbType.Int, 3906)
con.ConnectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test"
con.Open()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters("#PlaceID").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
con.Close()
I get the error;
An SqlParameter with ParameterName
'#PlaceID' is not contained by this
SqlParameterCollection.
Does anyone see what I'm doing wrong / have any suggestions how I can fix it? Code examples would be very helpful and any help is much appreciated.
You aren't actually adding the parameter to the cmd.Parameters collection:
cmd.Parameters.Add(par)
Alternatively, just add the parameter without instantiating the Parameter object explicitly:
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
Also, I'd follow the principle of using a variable as close to the declaration as possible and reorganize things this way:
Dim con As New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test")
con.Open()
Dim cmd As New SqlCommand("esp_getDates", con)
Try
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
cmd.ExecuteNonQuery()
Finally
If cmd IsNot Nothing Then cmd.Dispose()
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close()
End Try