Why System.Data.Sqlite is not displayed in References? - vb.net

I installed SQLite NuGet package using :
PM> NuGet\Install-Package SQLite -Version 3.13.0
Tentative de collecte d'informations de dépendance pour le package 'SQLite.3.13.0' du projet 'FindDoublons', ciblant '.NETFramework,Version=v4.7.2'
La collecte des informations de dépendance a pris 2 ms
Tentative de résolution de dépendances pour le package 'SQLite.3.13.0' avec DependencyBehavior 'Lowest'
La résolution des informations de dépendance a pris 0 ms
Actions en cours de résolution pour installer le package 'SQLite.3.13.0'
Actions résolues pour installer le package 'SQLite.3.13.0'
Récupération du package 'SQLite 3.13.0' dans 'nuget.org'.
Ajout du package 'SQLite.3.13.0' au dossier 'C:\Users\berna\source\repos\FindDoublons\packages'
Package 'SQLite.3.13.0' ajouté au dossier 'C:\Users\berna\source\repos\FindDoublons\packages'
Package 'SQLite.3.13.0' ajouté à 'packages.config'
Installation réussie de « SQLite 3.13.0 » sur FindDoublons
L'exécution des actions de nuget a pris 665 ms
Temps écoulé : 00:00:00.9417323
PM>
I use it in a VB.Net program using Visual Studio 2019 on Windows 11. But when I display References in Project Properties I don't see System.Data.Sqlite .Net assembly :
Is it normal System.Data.Sqlite is not displayed in References panel? What can I do to unlock my blocking situation?

Download/install NuGet package System.Data.SQLite instead.
Add Imports:
Imports System.Data.SQLite
Open Solution Explorer:
In VS menu, click View
Select Solution Explorer
To see references
In Solution Explorer, expand "References"
Here's some sample code:
Imports System.Data.SQLite
Imports System.IO
Module HelperSQLite
Private _connectionString As String = String.Empty
Private _databaseFilename As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Test.sqlite")
Sub New()
'set value
_connectionString = $"Data Source={_databaseFilename};Version=3;"
End Sub
Public Property DatabaseFilename As String
Get
Return _databaseFilename
End Get
Set(value As String)
_databaseFilename = value
_connectionString = $"Data Source={value};Version=3;"
End Set
End Property
Public Sub CreateDatabaseAndTable()
If Not File.Exists(DatabaseFilename) Then
SQLiteConnection.CreateFile(DatabaseFilename)
Dim sqlText As String = "CREATE TABLE Employee(
ID INTEGER Constraint PK_Employee_ID PRIMARY KEY AUTOINCREMENT,
FirstName TEXT,
LastName TEXT
);"
Debug.WriteLine($"_connectionString (CreateDatabaseAndTable): '{_connectionString}'")
Using con As SQLiteConnection = New SQLiteConnection(_connectionString)
'open
con.Open()
Using cmd As SQLiteCommand = New SQLiteCommand(sqlText, con)
cmd.ExecuteNonQuery()
End Using
End Using
End If
End Sub
Public Function GetData() As DataTable
Dim dt As DataTable = New DataTable()
Dim sqlText As String = "SELECT ID, FirstName, LastName FROM Employee;"
Debug.WriteLine($"_connectionString (GetData): '{_connectionString}'")
Using con As SQLiteConnection = New SQLiteConnection(_connectionString)
'open
con.Open()
Using da As SQLiteDataAdapter = New SQLiteDataAdapter(sqlText, con)
'get data
da.Fill(dt)
Return dt
End Using
End Using
End Function
Public Function GetDataAsString() As String
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
Dim dt As DataTable = GetData()
For Each row As DataRow In dt.Rows
sb.AppendLine($"ID: {row.Field(Of Int64)("ID")} FirstName: '{row.Field(Of String)("FirstName")}' LastName: '{row.Field(Of String)("LastName")}'")
Next
Return sb.ToString()
End Function
Public Function InsertData(firstName As String, lastName As String) As Integer
Dim sqlText As String = "INSERT INTO Employee(FirstName, LastName) VALUES(#firstName, #lastName);"
Debug.WriteLine($"_connectionString (InsertData): '{_connectionString}'")
Using con As SQLiteConnection = New SQLiteConnection(_connectionString)
'open
con.Open()
Using cmd As SQLiteCommand = New SQLiteCommand(sqlText, con)
If Not String.IsNullOrEmpty(firstName) Then
cmd.Parameters.Add("#firstName", DbType.String).Value = firstName
Else
cmd.Parameters.Add("#firstName", DbType.String).Value = DBNull.Value
End If
If Not String.IsNullOrEmpty(lastName) Then
cmd.Parameters.Add("#lastName", DbType.String).Value = lastName
Else
cmd.Parameters.Add("#lastName", DbType.String).Value = DBNull.Value
End If
'execute
Return cmd.ExecuteNonQuery()
End Using
End Using
End Function
End Module
Usage - Create database and table:
CreateDatabaseAndTable()
Usage - Insert data:
InsertData("Bob", "Smith")
InsertData("John", "Doe")
Usage - Select:
Dim results As String = GetDataAsString()
Debug.WriteLine(results)
Resources:
System.Data.SQLite
SQLite Data Types
SQLite Data Types (SQLite)
Parameters
Creating SQLite Database and Table in C# Console

Related

Load Records using the ADODB Connection with Datagridview

So i have here my codes for fetching informations from the database using
the listview, and now i want to use the datagridview but i dont know how
to do it using the ADODB Connectionenter image description here.
If you are able to use an Odbc connection instead try this to retreive your data
Dim conn As New OleDb.OleDbConnection("path to your database")
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim sql as String
Sql = "your SQL Query"
conn.Open()
cmd.Connection = conn
cmd.CommandText = Sql
da.SelectCommand = cmd
You can try using Odbc Connection in VB.Net.
First add new Module named Connection.vb
Imports System.Data.Odbc
Module Connection
Public Con As New OdbcConnection
Public Adpt As New OdbcDataAdapter
Public Ds As New DataSet
Public Cmd As OdbcCommand
Public Read As OdbcDataReader
Public Sql As String
Public StrCon As String = "Dsn=Your DSN Name in Odbc Connector"
Public Sub Connect()
Con = New OdbcConnection(StrCon)
If Con.State <> ConnectionState.Closed Then Con.Close()
Con.Open()
End Sub
End Module
And next don't forget to add Imports System.Data.Odbc in every form you have to connect to your Odbc Connection.
Simple Code to add item on ComboBox from Database.
Call Connect()
Cmd = New OdbcCommand("SELECT * FROM `category` ", Con)
cmbKategori.Items.Clear()
cmbKategori.AutoCompleteCustomSource.Clear()
Read = Cmd.ExecuteReader()
If Read.HasRows = True Then
While Read.Read()
cmbKategori.AutoCompleteCustomSource.Add(Read("name_category"))
cmbKategori.Items.Add(Read("name_category"))
End While
End If

Error In getting data from DataTableReader

as title say's im not being able to get my data from datatable, it's because im using innerjoin , if i only use one table it work's fine, as soon as i put inner join it gives me this error :
seems like the error its in sql sentence, because it don't return any value to datareader.
"System.InvalidOperationException: 'O DataTableReader é inválido para o DataTable atual ''.'"
here goes the code
Dim sql As String = "SELECT * FROM TOTAIS INNER JOIN FAT_PRODS ON TOTAIS.ID_FAT=FAT_PRODS.ID_FAT WHERE FAT_PRODS.ID_FAT=" + DataGridView1.SelectedRows(0).Cells(1).Value.ToString + ""
Dim dadosretornados As System.Data.DataTableReader = buscadadosacess(sql)
If dadosretornados.HasRows Then
While dadosretornados.Read
MsgBox(dadosretornados("ID_PROD"))
End While
End If
here is the function buscadados
Function buscadadosacess(sql As String)
oConn.ConnectionString = strConn
oConn.Open()
If oConn.State = ConnectionState.Open Then
ACommand = New OleDbCommand(sql, oConn)
'define um dataAdapter
AAdapter = New OleDbDataAdapter()
AAdapter.SelectCommand = ACommand
'define e preenche um DataTable com os dados
ATabela = New DataTable()
AAdapter.Fill(ATabela)
' associar campos a base de dados
xy = ATabela.CreateDataReader
' Ler da tabela
'linha = ACommand.ExecuteReader
End If
'Tipo de dados incorrecto na expressão de critérios.'
Return xy
End Function
thanks guys <3
the error was just a "." in the SQL Setence, here it goes the SQL SENTENCE Correct:
Dim sql As String = "select totais.id_fat,totais.valor_siva,totais.iva,totais.valortotal,totais.data,totais.nome_cliente,fat_prods.id_fat,fat_prods.id_prod,fat_prods.quantidade,fat_prods.preco,fat_prods.id_cliente,fat_prods.descricao from totais INNER JOIN fat_prods ON totais.id_fat=fat_prods.id_fat WHERE totais.id_fat=" + valor.ToString + ""
thanks for all the help

Path to Access Database in Visual Studio 2015

I'm working on a project in VB.NET, using Visual Studio 2015. My goal is that the user can create contacts, which the program puts in an Access database and lists in a DataGridView. I am using the following connection string:
Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Jacob\Documents\Visual Studio 2015\Projects\Accustomer\Accustomer\Global.accdb
This works fine when I publish it to my own PC, but the problem is that when I try to run it on another PC, it does not work because of the data source path not existing on that PC(pretty logic). I have tried to use "Data Source = Global.accdb". This works for displaying the data, but not for implementing the data into the database. Is there any way that the program recognizes the database without implementing the full path to the database?
As said in comments by krish,you should "build" your own path...so everytime you run you programm on another machine YOUR CODE creates the path using the right parameters.
You dont give a fix path, your code creates the right one for every machine it runs on. So the filename can be hardcoded, but the path to it should be "flexible".
In krish example [projectPath] and [db] are variables, that contain the right values depending on the PC.
$"Provider=Microsoft.ACE.OLEDB.12.0; Data Source = {projectPath}\{db}\Global.accdb"
What's presented below has already been mentioned and is correct, here I'm simply showing a full working example.
I created a class named Operations with a public (could be private) variable to create a connection string where the connection points to Global.accdb in the same folder as the application's executable file. If the database were a folder below you would add that path in the IO.Path.Combine right before the hard coded string. Note I used AppDomain.CurrentDomain.BaseDirectory as Application.StartupPath is not always available in other types of projects.
Create the connection string.
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Global.accdb")
}
Now here is the full code which I wrote for replying to questions for constructing not only the connection but for read/add/update and delete encapsulated into a single class for simplicity.
Public Class Operations
''' <summary>
''' Points to Global.accdb in the same folder as the application's
''' executable file
''' </summary>
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Global.accdb")
}
Public Sub New()
If Not IO.File.Exists(Builder.DataSource) Then
Throw New IO.FileNotFoundException("Failed to find application's database")
End If
End Sub
Public Sub GetCustomerData()
Dim DataTable As New DataTable
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
SELECT Identifier, ContactTitle, Country, CompanyName
FROM Customers
ORDER BY CompanyName ASC
</SQL>.Value
cn.Open()
DataTable.Load(cmd.ExecuteReader)
End Using
End Using
End Sub
Public Function AddNewRow(ByVal Name As String, ByVal Contact As String, ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
INSERT INTO Customer
(
CompanyName,
ContactName
)
Values
(
#CompanyName,
#ContactName
)
</SQL>.Value
cmd.Parameters.AddWithValue("#CompanyName", Name)
cmd.Parameters.AddWithValue("#ContactName", Contact)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
Public Function UpdateCustomer(ByVal CustomerId As Integer, ByVal Name As String, ByVal Contact As String) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText =
<SQL>
UPDATE Customer
SET CompanyName = #CompanyName, ContactName = #ContactName
WHERE Identifier = #Identifier
</SQL>.Value
cmd.Parameters.AddWithValue("#CompanyName", Name)
cmd.Parameters.AddWithValue("#ContactName", Contact)
cmd.Parameters.AddWithValue("#Identifier", Contact)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
Public Function DeleteCustomer(ByVal CustomerId As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "DELETE FROM Customers WHERE Identifier = #Identifier"
cmd.Parameters.AddWithValue("#Identifier", CustomerId)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

ERROR - Command text was not set for the command object

I am creating a program to book tickets for a school performance, this section of code displays dates from a database into a list box, then it gets the selected value and checks the databse with that name for the available seats.
Public ds As New DataSet 'used to store the basic elements of the database
Public con As New OleDb.OleDbConnection 'used to connect to the database
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Public datafile As String = "Resources/database.accdb" 'database location and version
Public da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sqlstatement, con)
Public sqlstatement As String
Public connString As String = provider & datafile
Public UserbeingEdited As String
Public sSelectedAssetType As String
ds.Clear()
con.ConnectionString = connString
con.Open()
sqlstatement = "SELECT ShowDate FROM AvailableDates"
da.Fill(ds, "Dates")
lbxDates.ValueMember = "ShowDate"
lbxDates.DisplayMember = "ShowDate"
lbxDates.DataSource = ds.Tables("Dates")
con.Close()
Private Sub lbxDates_SelectedValueChanged(sender As Object, e As EventArgs) Handles lbxDates.SelectedValueChanged
Dim oDataRowView As DataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
lbxActs.Items.Clear()
lbxActs.Items.AddRange(IO.File.ReadAllLines("Resources/" & sSelectedAssetType & ".txt"))
sSelectedAssetType = oDataRowView("ShowDate").ToString
For Each btn As Control In Seating_Plan.Controls
If checkSeats(btn.Name()) = "True" Then
SeatCount = SeatCount + 1
End If
Next
I keep getting this error and i dont know how to fix it, please help :)
The contents of a string object cannot be changed after the object is created.
If you want to use a variable to store the SQL query creates the variable and sets its value before assigning it to OleDbDataAdapter.
Public ds As New DataSet 'used to store the basic elements of the database
Public con As New OleDb.OleDbConnection 'used to connect to the database
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Public datafile As String = "Resources/database.accdb" 'database location and version
Public da As OleDb.OleDbDataAdapter
Public sqlstatement As String
Public connString As String = provider & datafile
Public UserbeingEdited As String
Public sSelectedAssetType As String
ds.Clear()
con.ConnectionString = connString
con.Open()
sqlstatement = "SELECT ShowDate FROM AvailableDates"
da = new OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "Dates")
lbxDates.ValueMember = "ShowDate"
lbxDates.DisplayMember = "ShowDate"
lbxDates.DataSource = ds.Tables("Dates")
con.Close()

How to extract data from Access db and place it into a text box using vb.net?

Hi guys I'm trying to search an employee information using SQL from MS Access, and hoping to put the fname lname and such details in their respective textbox which correspond to a specific employee's ID number. I have managed to make the SQL work but I don't know how to extract files from my sql statement and place it inside .text(text box), can you please guide me? Thanks
Here is my code so far:
(UPDATED my code) got an error message : Additional information: ExecuteReader: Connection property has not been initialized. Highlighting Reader below. How can i fix this? I'm trying to extract data and place it into the textbox? Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("fname")
empLnameText.Text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
for this, you need only this classes: Connection, Command, Reader.
Other classes in the code in question, some are redundant and some are required but in complicated than a simple case presentation.
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.text = reader("fname")
TextBox2.text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
call the method so:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
EDIT - Use parameters:
Private Sub QueryData(PathDb As String, command As String, id As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
com.Parameters.AddWithValue("", id)
connection.Open()
Using reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.Text = reader("fname")
TextBox2.Text = reader("lname")
End If
End Using
connection.Close()
End Using
End Using
End Sub
Call the method:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID = ?"
Dim empNum = "..."
QueryData(path, command, empNum)