Visual Basic 2015 SQLite Update Query not working - vb.net

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

Related

Insert Into data from other table vb . net access OleDb

I have different tables on same database , and i need to insert ID's of data from combobox.
Here's client table
what i need is to get id from combobox selected item and put it on the final table,
this is what i try
cmd.Parameters.AddWithValue("Client", client.Text)
Private Sub livbtn_Click(sender As Object, e As EventArgs) Handles livbtn.Click
'ModePaiement()
Try
SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client "
Execute(SQL, "Insert")
MessageBox.Show("The record has been saved.", "",
MessageBoxButtons.OK, MessageBoxIcon.Information)
ResetMe()
Catch ex As Exception
MessageBox.Show("" & ex.Message, "",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
and not working for sure , please help !
here's Module data connection:
Option Explicit On
Option Strict On
Imports System.Data.OleDb
Module AccessDB_Connection
Public Function GetConnectionString() As String
Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & Application.StartupPath & "\BLdatabase.accdb;Persist Security Info = false;"
Return strCon
End Function
Public con As New OleDbConnection(GetConnectionString())
Public cmd As OleDbCommand
Public SQL As String = String.Empty
Public Function PerformCRUD(Com As OleDbCommand) As DataTable
Dim da As OleDbDataAdapter
Dim dt As New DataTable()
Try
da = New OleDbDataAdapter
da.SelectCommand = Com
da.Fill(dt)
Return dt
Catch ex As Exception
MessageBox.Show("" & ex.Message)
End Try
Return dt
End Function
End Module
thank's everybody for replying;
so here's execute method :
Private Sub Execute(MySQL As String, Optional Parameter As String = "")
cmd = New OleDbCommand(MySQL, con)
AddParameters(Parameter)
PerformCRUD(cmd)
End Sub
Private Sub AddParameters(str As String)
cmd.Parameters.AddWithValue("Client", client.Text)
End Sub
Public Function PerformCRUD(Com As OleDbCommand) As DataTable
Dim da As OleDbDataAdapter
Dim dt As New DataTable()
Try
da = New OleDbDataAdapter
da.SelectCommand = Com
da.Fill(dt)
Return dt
Catch ex As Exception
MessageBox.Show("" & ex.Message)
End Try
Return dt
End Function
so it's very simple , i need to store an id value from an selected item :
enter image description here
here's an example , i need to store that value 26 from that table client to other table when i select IMAX client from combobox
enter image description here
enter image description here
there's 2 different results it depends on the query used :
with SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client " --> there's nothing happened
with SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) values(SELECT code_client from client WHERE client = #Client) "
--> error
enter image description here
The issue I see, you are trying to run:
SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client "
However, in your PerformCRUD method, you are filling a data adapter and returning a DataTable based on an INSERT where ExecuteNoQuery is the method to use.
Here is an example (More Info):
Using cmd = con.CreateCommand()
cmd.CommandText = SQL
'It is good practice to specify the data type. Note: 80 in this example is the column size/length.
cmd.Parameter.Add("#Client", OleDbType.VarChar, 80).Value = client.Text
cmd.Connection = con
con.Open() 'if not already open
cmd.ExecuteNonQuery()
End Using

vb.net how to get Select ##Identity

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

VB Access Update data type mismatch

Sorry in advance, Im new to vb,
Im creating a small application for assignment as a MCQ quiz, Im using the same form but use the function of [nextques] proceed to next question and use [answer] to update the user answer to database(access).
I previously uses SQL Server and it work good but due to i need to run the application in school's computer where they wont allow me to install anything, I have no idea at all then decided to use access as it is easier to export and include it in debug file.
Ive go through some topics as well as did some changes however the problem persist. I set the [input] in access as integer, i did put parameter on it but it still not working.
ERROR code : Data type mismatch in criteria expression
Public Function answer(ans As Integer)
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=mom.mdb;"
con.Open()
cmd.Connection = con
' Update the answer 1234 (as abcd) according to id in lblnum.text
Dim updatecmd As String = "UPDATE question SET [input] = #ans WHERE id = '" & lblnum.Text & "'"
cmd.Parameters.AddWithValue("#ans", ans)
cmd.CommandText = updatecmd
updatecmd = cmd.ExecuteNonQuery()
con.Close()
'Proceed to next question by calling Function NextQues
nextques()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return 0
End Function
I tried also to make it like this however another error shows: COM object that has been separated from its underlying RCW cannot be used
Public Function answer(ans As Integer)
Dim countid As Integer = 1
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=mom.mdb;"
con.Open()
cmd.Connection = con
Dim updatecmd As String = "UPDATE question SET [input] = #ans WHERE id = #countid"
cmd.Parameters.AddWithValue("#countid", countid)
cmd.Parameters.AddWithValue("#ans", ans)
cmd.CommandText = updatecmd
updatecmd = cmd.ExecuteNonQuery()
countid = countid + 1
con.Close()
'Proceed to next question by calling Function NextQues
nextques()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return 0
End Function
change this line
Dim updatecmd As String = "UPDATE question SET [input] = #ans WHERE id = '" & lblnum.Text & "'"
to
Dim updatecmd As String = "UPDATE question SET [input] = #ans WHERE id = " & lblnum.Text

Executing update query inside loop

cmd = New SqlCommand("select enrollment,total_fee,discount,net_fee from stu_dtl", openConnection())
' dr = cmd.ExecuteReader
adpt = New SqlDataAdapter(cmd)
adpt.Fill(ds, "stu_dtl")
dt = ds.Tables("stu_dtl")
For i = 0 To dt.Rows.Count - 1
cmd = New SqlCommand("update stu_dtl set net_fee = '" & (Val(dt.Rows(i).Item("total_fee")) - Val(dt.Rows(i).Item("discount"))) & "' where enrollment = '" & dt.Rows(i).Item("enrollment") & "'", openConnection())
cmd.ExecuteNonQuery()
Next
when I execute this code for more than 150 records "Nothing happens"......what am i doing wrong??is there any other way to update??
I'm not sure what you are doing wrong. But try this code. If an error occur it ensure rollback of the database. Note that I assume that the datatype of the net_fee and enrollment columns are Integer.
Using connection As SqlConnection = New SqlConnection("TODO: Set connection string.")
Dim table As DataTable = New DataTable("stu_dtl")
Dim [error] As Exception = Nothing
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "SELECT [enrollment], [total_fee], [discount], [net_fee] FROM [stu_dtl];"
Using adapter As New SqlDataAdapter(command)
adapter.Fill(table)
End Using
End Using
Using transaction As SqlTransaction = connection.BeginTransaction()
Try
Dim net_fee As Integer = 0
Dim enrollment As Integer = 0
For Each row As DataRow In table.Rows
net_fee = (CInt(row.Item("total_fee")) - CInt(row.Item("discount")))
enrollment = CInt(row.Item("enrollment"))
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "UPDATE [stu_dtl] SET [net_fee] = #net_fee WHERE [enrollment] = #enrollment;"
command.Parameters.AddWithValue("#net_fee", net_fee)
command.Parameters.AddWithValue("#enrollment", enrollment)
command.ExecuteNonQuery()
End Using
Next
transaction.Commit()
Catch ex As Exception
[error] = ex
transaction.Rollback()
End Try
End Using
If (Not table Is Nothing) Then
table.Dispose()
table = Nothing
End If
If (Not [error] Is Nothing) Then
Throw [error]
End If
End Using
Edit
Come to think of it, you might want to change the net_fee column to a computed column. The formula would simply be ([total_fee] - [discount]).

Storing ID from SQL result

Im running the following code to tell if a user excists on a database - standard stuff. Obviously once the code is run a boolean true or false will be returned if there is a result. If a result is found i want to store the ID of the said result. Can anyone tell me how'd id go about doing this?
code:
Username = txtUserName.Text
Password = txtPassword.Text
dbConnInfo = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\techs.mdb"
con.ConnectionString = dbConnInfo
con.Open()
Sql = "SELECT * FROM techs WHERE userName = '" & Username & "' AND '" & Password & "'"
LoginCommand = New OleDb.OleDbCommand(Sql, con)
CheckResults = LoginCommand.ExecuteReader
RowsFound = CheckResults.HasRows
con.Close()
If RowsFound = True Then
MsgBox("Details found")
TechScreen.Show()
Else
MsgBox("Incorrect details")
End If
There are a lot of problems with the code snippet you posted. Hopefully, I can help you correct these problems.
In order to load the ID of the result you'll want to use SqlCommand.ExecuteScalar() as this is optimized to pull back one result from Sql.
As to what is wrong with your code, you're wide open to Sql Injection attacks and you should be using Parametrized Queries as shown in my sample below.
Public Function AddProductCategory( _
ByVal newName As String, ByVal connString As String) As Integer
Dim newProdID As Int32 = 0
Dim sql As String = _
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); " _
& "SELECT CAST(scope_identity() AS int);"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar)
cmd.Parameters("#Name").Value = newName
Try
conn.Open()
newProdID = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return newProdID
End Function
Source: MSDN