vb.net how to get Select ##Identity - vb.net

i have this code [Sample 1] and it is working.
It show me ID for actual inserted data from Access, but I would like to use something like in [Sample 2], but i still don't know find out how to write right code for that. :(
Sample 1 [working]
Dim query As String = "Insert Into REGISTER (DC,Price) Values (?,?)"
Dim FindID As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\sourcepath\db.accdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
conn.Open()
cmd.Parameters.AddWithValue("", Format(Now, "yy") & Format(DatePart(DateInterval.WeekOfYear, Now), "00"))
cmd.Parameters.AddWithValue("", PriceTextBox.Text)
cmd.ExecuteNonQuery()
cmd.CommandText = FindID
ID = cmd.ExecuteScalar()
conn.Close()
End Using
End Using
Sample 2 [here I need help]
This code write data to Access but I can't get the ID.
(Part for get ID isn't in code)
Dim rw As DataRow
rw = RegisterDBDataSet.REGISTER.NewRow
rw.Item("Price") = Format(Now, "dd.MM.yyyy")
rw.Item("DC") = Format(DatePart(DateInterval.WeekOfYear, Now), "00"))
Try
RegisterDBDataSet.REGISTER.Rows.Add(rw)
REGISTERTableAdapter.Update(RegisterDBDataSet.REGISTER)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
what must i put into code for get ID in sample 2?
thanks

You should add an handler for the RowUpdated event of the OleDbDataAdapter, then in this handler execute your command to retrieve the Identity value generated by your query
RegisterDBDataSet.REGISTER.Rows.Add(rw)
AddHandler REGISTERTableAdapter.RowUpdated, AddressOf(rowUpdateEvent)
REGISTERTableAdapter.Update(RegisterDBDataSet.REGISTER)
.....
Sub rowUpdateEvent(sender As Object , args As OleDbRowUpdatedEventArgs)
Dim identity = "SELECT ##IDENTITY"
Dim cmd = New OleDbCommand(identity, args.Command.Connection)
ID = cmd.ExecuteScalar()
End Sub
Of course that ID variable is global to your form code

Related

Converting VBA function to VB.net to get sql data

I am trying to convert VBA code into VB.net and I have made it to a point but I can't convert resultset into vb.net. RS was 'dim as resultset' in VBA, thought i could just change it to dataset but am getting errors with the '.fields' and other options?
Function GetG(sDB As String, sServ As String, sJob As String) As String
'sDB = Database name, sServ = Server\Instance, path = job.path
Dim conString As String = ("driver={SQL Server};server = " &
TextBox1.Text & " ; uid = username;pwd=password:database = " &
TextBox2.Text)
Dim RS As DataSet
Dim conn As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand
conn.Open()
'This is where my problems are occuring
cmd = New SqlCommand("SELECT [ID],[Name] FROM dbo.PropertyTypes")
Do While Not RS.Tables(0).Rows.Count = 0
If RS.Fields(1).Value = sJob Then
GetG = RS.Fields(0).Value
GetG = Mid(GetG, 2, 36)
Exit Do
End If
DataSet.MoveNext
Loop
conn.Close
End Function
Based on my understanding and some guesswork, here is what I came up with for what I think you're wanting.
As I stated in my comment above, it appears you can just use a WHERE clause to get the exact record you want (assuming a single instance of sJob appears in the name column).
Build the connectionstring off the input arguments, not controls on your form. That is after all why you allow for arguments to be passed along. Also note that there is a SqlCommandBuilder object that may be of interest. But for now
Function GetG(sDB As String, sServ As String, sJob As String) As String
'we'll pretend your connectionstring is correct based off of the sDB and sServ arguments
Dim conStr As String = ("driver={SQL Server};server = " & sServ & " ; uid = username;pwd=password:database = " & sDB)
'Create a connection and pass it your conStr
Using con As New SqlConnection(conStr)
con.Open() 'open the connection
'create your sql statement and add the WHERE clause with a parameter for the input argument 'sJob'
Dim sql As String = "SELECT [ID], [Name] FROM dbo.PropertyTypes WHERE [Name] = #job"
'create the sqlCommand (cmd) and pass it your sql statement and connection
Using cmd As New SqlCommand(sql, con)
'add a parameter so the command knows what #job holds
cmd.Parameters.Add(New SqlParameter("#job", SqlDbType.VarChar)).Value = sJob
'Now that have the command built, we can pass it to a reader object
Using rdr As SqlDataReader = cmd.ExecuteReader
rdr.Read()
'i admin i'm a little confused here on what you are
'trying to achieve so ID may not be what you are
'really wanting to get a substring of.
Return rdr("ID").ToString.Substring(2, 36)
End Using
End Using
End Using
End Function
An example to see if this is working could be to call a messagebox do display the result. For this example, I'm going to pretend that TextBox3 holds the sJob you're wanting. With that knowledge, you could simply do:
MessageBox.Show(GetG(TextBox2.Text, TextBox1.Text, TextBox3.Text))
This should then produce the result in a messagebox.
It seems that you're not filling your DataSet. So, when you try to loop through it, it's uninitialized or empty.
Check this answer to see an example: Get Dataset from DataBase

Visual Basic 2015 SQLite Update Query not working

I used NuGet Package Manager to install SQLite package in my Visual Basic 2015 Project so that i can use it in my application. The problem i am facing is that i have a sub in my application whose code is indicated below that i am using to update a table in SQLite but it does not update the values.
AddErrors is another sub that adds the errors that are captured by the try catch to the same SQLite database but different table and works fine. Can you tell me what i am doing wrong.
I have tried both the commented and the uncommitted code with both not updating the database and not throwing any errors.
Public Sub PostedLink(ByVal id As String, ByVal link As String)
Dim query As String = "UPDATE Table SET torf = 1 , link = '" & link & "' WHERE id = '" & id & "';"
Dim affectedRows As Integer = 0
Try
Using con As New SQLiteConnection(connectionString)
con.Open()
Using cmd As New SQLiteCommand(con)
cmd.CommandTimeout = 20
cmd.CommandText = query
'Dim dr As SQLiteDataReader
'dr = cmd.ExecuteReader()
affectedRows = cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
Catch ex As Exception
AddErrors("Updating table", ex.ToString)
End Try
End Sub
The table i am trying to update has the following structure.
CREATE TABLE Table
(
id VARCHAR(100) PRIMARY KEY NOT NULL,
text VARCHAR(100),
link VARCHAR(254) DEFAULT "",
torf BOOLEAN NOT NULL DEFAULT 0
);
Solution by OP.
I changed the code to use parameterized query as follows and it worked flawlessly.
Public Sub PostedLink(ByVal id As String, ByVal link As String)
Dim query As String = "UPDATE Table SET torf = 1, link = #link WHERE id = #id;"
Dim affectedRows As Integer = 0
Try
Using con As New SQLiteConnection(connectionString)
con.Open()
Using cmd As New SQLiteCommand(con)
cmd.CommandTimeout = 20
cmd.CommandText = query
With cmd.Parameters
.Add(New SQLiteParameter("#link", link))
.Add(New SQLiteParameter("#id", id))
End With
'Dim dr As SQLiteDataReader
'dr = cmd.ExecuteReader()
affectedRows = cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
Catch ex As Exception
AddErrors("Updating table", ex.ToString)
End Try
End Sub

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

I am getting this error "There is no row at position 0." vb.net as the frontend and sql server 2008 as the db

This is my code, I m getting error "There is no row at position 0."
Sub loadservicetype()
Dim str As String = "SELECT servicename FROM tbl_activity WHERE activity= '" & CmbActivity.Text & "' "
Dim dt As New DataTable
Dim sdr As New SqlDataAdapter(str, connection)
sdr.Fill(dt)
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End Sub
First thing is Always Use SQL Parameter to AVOID SQL injection
Like this
Dim commandText As String = "SELECT servicename FROM tbl_activity WHERE activity=#ID"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
command.Parameters.Add("#ID", SqlDbType.Int).Value = ID
Try
connection.Open()
Dim rowsAffected As String = command.ExecuteNonQuery()
Catch ex As Exception
throw
End Try
End Using
MSDN SOURCE
Your DataTable is Doesn't Return any rows which You Are Trying to Access
If dt IsNot Nothing Then
If dt.Row.Count>0 Then
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End If
End If

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub