VB NET AND SQLITE : file is encrypted or is not a database - vb.net

I am trying to create an apps with VB.NET and SQLite, i have create the database and table with SQLiteManager and I HAVE SET ENCRYPTION TO THE DATABASE and THE PASSWORD IS SAME AS WHAT IN THE CONNECTION STRING.
However when i am trying to insert sample record to table, it gave an error file is encrypted or is not a database
This is the sample of the code that produce the error.
Using ConLite = OpenConLite()
Using LiteCmd As New SQLiteCommand
Dim TglWaktuSekarang As String = CurrentDateTime()
LiteCmd.CommandText = "INSERT INTO finger_stamp(emp_id,emp_name,date_time) VALUES('1','DIANA','" & TglWaktuSekarang & "')"
LiteCmd.CommandType = CommandType.Text
LiteCmd.Connection = ConLite
LiteCmd.ExecuteNonQuery()
End Using
End Using
and this is my connection code
Public Function OpenConLite() As SQLiteConnection
Dim SQLiteCon As SQLiteConnection
Try
Dim ConLiteString As String = "Data Source=C:\SQLiteDB\attendance.sqlite;Version=3;Password=hahaha;"
SQLiteCon = New SQLiteConnection(ConLiteString) ' Connection DataSource
SQLiteCon.Open()
OpenConLite = SQLiteCon
Catch ex As Exception
OpenConLite = Nothing
MsgBox("Failed to connect to Database", MsgBoxStyle.Information, "Warning")
End Try
End Function

Related

"No value given for one or more required parameters" error using OleDbCommand

I am trying to update a record in MS Access using VB.net. This code will be under the "Delivered" button. When I try to run it, it shows the "No value given for one or more required parameters" error. Here is my code:
Private Const strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Traicy\Downloads\MWL(11-30-2021)\MadeWithLove\MadeWithLove\MadeWithLove.mdb;"
ReadOnly conn As OleDbConnection = New OleDbConnection(strConn)
Dim cmd As OleDbCommand
Public Sub DeliveredUpdate()
Const SQL As String = "UPDATE DELIVERY SET delivery_status = #status"
cmd = New OleDbCommand(SQL, conn)
' Update parameter
cmd.Parameters.AddWithValue("#status", "Delivered")
' Open connection, update, then close connection
Try
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("The delivery status was successfully updated.")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
conn.Close()
End Try
End Sub
Do not declare connections or commands outside of the method where they are used. These database objects use unmanaged resources. They release these resources in their Dispose methods. The language provides Using blocks to handle this.
As mentioned in comments by Andrew Morton, you should have a Where clause to tell the database which record to update. This would contain the primary key of the record. I guessed at a name for the field, OrderID. Check your database for the real field name.
Access does not use named parameters but you can use names for readability. Access will be able to recognize the parameters as long as they are added to the Parameters collection in the same order that they appear in the sql string. In some databases the Add method is superior to AddWithValue because it doesn't leave the datatype to chance.
It is a good idea to separate your database code from your user interface code. If you want to show a message box in your Catch put the Try blocks in the UI code. This way your function can be used in a web app or mobile app without rewriting.
Public Function DeliveredUpdate(ID As Integer) As Integer
Dim recordsUpdated As Integer
Dim SQL As String = "UPDATE DELIVERY SET delivery_status = #status Where OrderID = #Id;"
Using conn As New OleDbConnection(strConn),
cmd As New OleDbCommand(SQL, conn)
cmd.Parameters.Add("#status", OleDbType.VarChar).Value = "Delivered"
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = ID
conn.Open()
recordsUpdated = cmd.ExecuteNonQuery
End Using 'closes and disposes the command and connection
Return recordsUpdated
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim retVal As Integer
Dim id As Integer = 1 'not sure where you are getting this value from
Try
retVal = DeliveredUpdate(id)
Catch ex As Exception
MsgBox(ex.Message)
End Try
If retVal > 0 Then
MsgBox("The delivery status was successfully updated.")
End If
End Sub

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

Having the ExecuteNonQuery : connection property has not been initialized

I'm trying to delete an entry from my database. But when the ExecuteNonQuery has to do it's job it can't find the enabled connection and give me this error :
System.InvalidOperationException :'ExecuteNonQuery : connection property has not been initialized'
Here is what I did :
Dim delete As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim dt As DataTable
initConnectionDtb(pathDtb)
openConnection()
If TextBox2.Text <> "" Then
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
MsgBox("USER HAS BEEN DELETED")
Else
MsgBox("ERROR")
End If
I could check if it was properly connected to the Database thanks to connectionName.State
I also enterily rewrote the connetion to the database in the function but ExecuteNonQuery still couldn't connect even though the connection was opened
I saw that i'm not the only one on this website but none of the previous answers have helped me.
#Filburt pointed out, how are you assigning your connection to your command object. Here is an example :
Using connection As OleDbConnection = New OleDbConnection(connectionString)
connection.Open()
Dim command As OleDbCommand = New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
End Using
In your code, you need to assign the connection object to your command object. We can't see what code you have in initConnectionDtb(pathDtb) or openConnection()
To adapt this to your code:
delete.Connection = <<your connection object here>>
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
Another note: look into parameterizing your query strings instead of hand stringing the values. This will prevent issues with TextBox2.Text having a value like O'Toole which will cause a syntax error as well as SQL Injection.
Here's what i used to initialize my connection :
Public Function initConnectionDtb(ByVal path As String) As Boolean
initConnectionDtb = True
Connection = New OleDbConnection
Try
Connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;" & "data source= " & path & ";"
Catch ex As Exception
Return False
End Try
End Function
Public Function openConnection() As Boolean
openConnection = True
Try
Connection.Open()
MsgBox(Connection.State) 'to test if my connection really openned in my previous post
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub closeConnection()
If Not IsNothing(Connection) Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
MsgBox(Connection.State)
Connection.Dispose()
Connection = Nothing
End If
End Sub
So far it worked for everything i tried (adding someone to the database for exemple)

attach 2 sqlite database and select tables

i have problem when i try to select join tables from different sqlite database with attach database command and put the value into datagridview
they get many error e.g: databases cannot open, ExuteNonQuery error, cannot open connection, cannot open databases.
pathinfo2 as my master db and pathinfo1 as my db2
this my code:
Sub slc_smscontact()
Dim fc1 As String = "Data Source=" + pathinfo2.Text + ";Version=3;"
Dim SQL As String = "ATTACH '" + pathinfo1.Text + "' AS db2"
Dim com As New SQLiteCommand(SQL)
Dim connection As SQLiteConnection = New SQLiteConnection(fc1)
'connection.ConnectionString = fc1
com.Connection = connection
connection.Open()
Dim retval As Integer = 0
Try
retval = com.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("An error occurred, your attach databases was not completed.")
Finally
com.Dispose()
End Try
SQL = "select distinct a.data1 no_telp, b.data1 nama, db2.sms.address, db2.sms.body, db2.sms.date, db2.sms.date_sent, db2.sms.Thread_id from (select raw_contact_id,data1 from data where mimetype_id = 5) as a, (select raw_contact_id,data1 from data where mimetype_id = 7) as b where a.raw_contact_id = b.raw_contact_id INNER JOIN db2.sms ON data.no_telp = db2.sms.address;"
com = New SQLiteCommand(SQL)
com.Connection = connection
'retval = 0
Try
Dim ds3 As New DataSet()
Dim da3 As New SQLiteDataAdapter(com)
da3.Fill(ds3)
grid3.DataSource = ds3.Tables(0).DefaultView
'retval = com.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("An error occurred, your select was not completed.")
Finally
'com.Dispose()
connection.Close()
End Try
End Sub
there are anyone know how to fix it?
This works fine for opening, attaching and querying a secondary db:
Dim SQL = "SELECT Id, Name, Fish, Bird FROM db2.Example"
' "attachment" string
Dim sqlAtt = String.Format("ATTACH '{0}' AS {1} ", sqlFile, "db2")
' connect to "main" db
Using dbcon As New SQLiteConnection(LiteConnStr)
' create a command just for the attaching
Using cmdAtt As New SQLiteCommand(sqlAtt, dbcon)
dbcon.Open()
' execute attachment
cmdAtt.ExecuteNonQuery()
' now run a query on db2 from connection to db1
Using cmd As New SQLiteCommand(SQL, dbcon)
dtSample = New DataTable
dtSample.Load(cmd.ExecuteReader)
dgv2.DataSource = dtSample
End Using
End Using
End Using
One of the things you want to do is to properly reference the db file to attach (and the main db file for that matter), and a TextBox (ie user input) is a bad start. Something like this:
sqlFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"SQLite dbs", "secondary.db")
Dim sqlAtt = String.Format("ATTACH '{0}' AS {1} ", sqlFile, "db2")
Enclosing the file name(s) in ticks helps prevent it from being incorrectly read when the path contains a space.
If/when you close (or dispose) the connection the attachment is lost, so you might want to create a method to open and attach the other db and return a DBConnection object.

How to handle database connectivity in entire project

I have created a function in a module to connect to database for a windows application
Imports System.Data.SqlClient
Module mod_main
Public Function connectDB() As SqlConnection
Dim Connection As New SqlConnection
Try
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
If IntegratedSecurity Then
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;Integrated Security=True"
Else
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;User ID='" & usr & "';Password='" & pwd & "'"
End If
Connection.Open()
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Module
I have so many functions and classes that uses plethora of db activities for that I use aforementioned connection function.For exmample:
Public Sub FillComboBox(ByVal ComboBox As C1.Win.C1List.C1Combo, ByVal Query As String, ByVal DisplayMember As String, ByVal ValueMember As String)
Dim SourceDataSet As New DataSet
Dim adapter As New SqlDataAdapter(Query, connectDB) /*Assigning connection here */
adapter.Fill(SourceDataSet)
ComboBox.DataSource = SourceDataSet.Tables(0)
ComboBox.ColumnHeaders = False
ComboBox.ColumnWidth = 0
ComboBox.ExtendRightColumn = True
ComboBox.DisplayMember = DisplayMember
ComboBox.ValueMember = ValueMember
End Sub
Since I'm a beginner in programming my question is , Is this a correct way of handling db connection?
I suggest you to make following changes:
make Connection as public for global accessibility
save connection string in config file and access it from there
need not to close and re open connection open connection only when there is no available connection
In your case all time it creates a new connection when the function is
invoked since you are declaring and initializing connection inside the
function. so checking connection state is meaning less:
so your function looks like following:
public Connection As New SqlConnection
Public Function connectDB() As SqlConnection
Try
Dim Constr As String =""
If IntegratedSecurity Then
Constr = ConfigurationManager.AppSetting("IconnectionString")
Else
Constr = ConfigurationManager.AppSetting("connectionString")
End If
If Connection Is Nothing Then
Connection = New SqlConnection(Constr)
End If
If Connection.State <> ConnectionState.Open Then
Connection.Open()
End If
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function