SQLite connection in sharpdevelop 4 - vb.net

I am struggling with some SQLite to VB.net code. I am using sharpdevelop 4.0 to try and connect to a SQLite database using SQLiteadmin. I have set up both and just need help in getting them to connect to each other when they mainform loads. I have put the code in mainform (see below) The database is called "KCB.db3". When i click the button i get an error message saying the connection is closed. What am i doing incorrectly?
Dim SQLconnect As New System.Data.SqlClient.SqlConnection
Dim SQLcommand As System.Data.SqlClient.SqlCommand
Dim SQLreader As System.Data.SqlClient.SqlDataReader
Sub Button1Click(sender As Object, e As EventArgs)
'Procedure to extract records from People table in Contacts SQLite database file
'Create an SQL command
SQLcommand = SQLconnect.CreateCommand
'Create SQL statement
SQLcommand.CommandText = "SELECT * FROM Staff"
'Extract data
SQLreader = SQLcommand.ExecuteReader()
While SQLreader.Read()
'Add record to listbox
msgbox(SQLreader("Staff_ID"))
msgbox(SQLreader("Staff_Surname"))
msgbox(SQLreader("Staff_First_Name"))
End While
'Clear SQL command buffer
SQLcommand.Dispose()
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
SQLconnect.ConnectionString = "data source = KCD.db3"
SQLconnect.Open()
End Sub
I hope someone out there can help! Thanks

You seem to be trying to use the Microsoft Sql Server client to connect to SQLite which is not going to work.
If you install SQLite using NuGet you can then change your variables to be the following types:
Dim SQLconnect As New System.Data.SQLite.SQLiteConnection
Dim SQLcommand As System.Data.SQLite.SQLiteCommand
Dim SQLreader As System.Data.SQLite.SQLiteDataReader
Then the rest of your code should work.
The above SQLiteConnection, SQLiteCommand and SQLiteDataReader classes are in the System.Data.SQLite assembly which will be referenced after you install the SQLite NuGet package.

Related

I just want to know the difference of these two in vb.net? Using Data adapter and Using the oledb command?

Private Sub Contestant_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim command As String
Dim dsSET As New DataSet
Dim connect As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\athan\Documents\PAGEANT.accdb")
command = "SELECT * from Contestant "
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(command, connect)
comSTR = "SELECT * from Contestant "
dsSET.Clear()
da.Fill(dsSET, "contest")
dgvContestant.DataSource = dsSET
dgvContestant.DataMember = "contest"
End Sub
I don't understand the above code but it still fetches data from the database and load it to datagridview.
Below is another code but throwing this error:
'Command text was not set for the command object.'
Private Sub Contestant_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dsSET As New DataSet
Dim connect As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\athan\Documents\PAGEANT.accdb")
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand
With cmd
.Connection = connect
.CommandText = "SELECT * from Contestant "
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(command, connect)
.Connection.Open()
.ExecuteNonQuery()
da.Fill(dsSET, "contest")
dgvContestant.DataSource = "contest"
.Connection.Close()
End With
End Sub
In the second code snippet, you're setting the CommandText of cmd but not setting the CommandText of command. It's command that that you then pass into the data adapter. Why do you have two command objects in the first place? If cmd is the command object whose CommandText you set then surely that should be the command object you pass into the data adapter.
A connection object creates a connection between your application and the database. SQL can be executed over that connection and data passed back and forth.
A command object contains SQL code and, optionally, the parameters for that SQL. A command is always associated with a connection over which it is executed. If the command contains a SELECT statement then you can call ExecuteScalar to retrieve a single value or ExecuteReader to retrieve zero, one or more records containing one or more columns. If the command does not contain a SELECT statement, you can call ExecuteNonQuery.
A data adapter is basically a group of up to four command objects to perform CRUD operations. When you call Fill, the SelectCommand is executed to retrieve data into a DataTable. When you call Update, the InsertCommand, UpdateCommand and DeleteCommand are executed as required to save changes from a DataTable to a database.
When you create a data adapter, you can either provide a ready-made command object for the SelectCommand or let the adapter create one itself. If you do the latter, you can pass the SQL code and an existing connection or you can pass the SQL code and a connection string, in which case the adapter will create the connection object too. A data adapter will not create its own InsertCommand, UpdateCommand and DeleteCommand so you have to create those yourself or, in certain circumstances, you can use a command builder to do it for you.
You might benefit from a look at my ADO.NET examples here.
A command is just a representation of a SQL statement and an associated connection. It can be executed in several ways, by returning a reader with .ExecuteReader, for Insert, Update and Delete statements with .ExecuteNonQuery and to retrieve a single value with .ExecuteScalar.
It can also be used by a DataAdapter.
A DataAdapter can not only .Fill a DataTable or DataSet but also .Update
Comments and explanations in line.
Private Sub Contestant_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Declares a variable as String
Dim command As String
'Creates a DataSet object. Note the New keyword
Dim dsSET As New DataSet
'Creates a Connection object and sets the .ConnectionString property by passing it to the Constructor of the object
Dim connect As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\athan\Documents\PAGEANT.accdb")
'Assigns a value to the previously declared String
command = "SELECT * from Contestant "
'Creates a DataAdapter object and provides a SQL Select statement that the adapter can use to create its SelectCommand property
'and sets the .Connection property by passing a Connection object.
'Note: the connection is NOT an open connection
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(command, connect)
'Undeclared and unnecessary variable
'comSTR = "SELECT * from Contestant "
'Unnecessary code - You just created, it is already empty
'dsSET.Clear()
'Calls the DatAdapter .Fill method passing the DataSet to fill and the name of the DataTable being filled.
'The .Fill method opens and closes the connection if it finds it closed. If the connection is already open
'the .Fill method leaves it open.
da.Fill(dsSET, "contest")
'The DataSet is set as DataSourd
dgvContestant.DataSource = dsSET
'Since a DataSet can contain more than one table; the .DataMember of the DataSet
'is set to the name of the DataTable to display.
dgvContestant.DataMember = "contest"
End Sub
Private Sub Contestant_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dsSET As New DataSet
Dim connect As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\athan\Documents\PAGEANT.accdb")
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand
With cmd
.Connection = connect
.CommandText = "SELECT * from Contestant "
'Here command is not declared
'Visual Studion assumes you mean Interaction.Command() which is NOT at all want you want
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(command, connect)
.Connection.Open()
'A DataAdapter does not have a .ExecuteNonQuery method
'.ExecuteNonQuery belongs to .Command and is used for SQL statements that
'begin with Insert, Update or Delete.
.ExecuteNonQuery()
da.Fill(dsSET, "contest")
'The .DataSoure of a DataGridView cannot be set to a String
dgvContestant.DataSource = "contest"
.Connection.Close()
End With
End Sub
'I don't think you need a DataAdapter or a DataSet
Private Sub FillDataGridView()
Dim dt As New DataTable
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\athan\Documents\PAGEANT.accdb"),
cmd As New OleDbCommand("SELECT * from Contestant ", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
'Update the User Interface after the connection is closed.
dgvContestant.DataSource = dt
End Sub

ComboBox.SelectedText Property and Database Error

This specific code ComboBox2.SelectedItem query has an error to my database. I think I'm missing something with this code ComboBox2.SelectedItem:
Private Sub UpdateCombo()
ComboBox2.Items.Clear()
SQLcon.Open()
Dim Command As SqlClient.SqlCommand = SQLcon.CreateCommand()
Command.CommandText = "Select productName From tblProductsStocks"
Dim SQLReader As SqlClient.SqlDataReader = Command.ExecuteReader()
While SQLReader.Read()
ComboBox2.Items.Add(SQLReader.Item("productName"))
End While
SQLcon.Close()
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
SQLcon.Open()
Dim Command As SqlClient.SqlCommand = SQLcon.CreateCommand()
Command.CommandText = "Select * From tblProductsStocks WHERE productName=" & ComboBox2.SelectedItem
Dim SQLReader As SqlClient.SqlDataReader = Command.ExecuteReader()
SQLReader.Read()
TextBox1.Text = SQLReader.Item("productType")
TextBox2.Text = SQLReader.Item("productMass")
SQLcon.Close()
End Sub
Please turn on Option Strict. This is a 2 part process. First for the current project - In Solution Explorer double click My Project. Choose Compile on the left. In the Option Strict drop-down select ON. Second for future projects - Go to the Tools Menu -> Options -> Projects and Solutions -> VB Defaults. In the Option Strict drop-down select ON. This will save you from bugs at runtime.
Connections need to be disposed as well as closed to be returned to the connection pool. If there is an error, your code may not even close the connection. If you keep your database objects local, you can control that they are closed and disposed. Using...End Using blocks take care of this for you even if there is an error. In my code the Command is part of the Using block. Note the comma after the connection constructor.
You can pass the connection string directly to the constructor of the connection. Likewise pass the command text and the connection to the command constructor.
Use parameters. Not only does it avoids errors concatenating strings but it also avoids Sql injection. In your code, the selected item is meant to be a string but you have failed to add the surrounding single quotes. This is not needed when you use parameters. Command text is executable code to the server and a malicious user can enter things that would ruin you database. Parameters are considered as values by the server, not executable code so they are much safer.
Open the connection at the last possible moment, right before the .Execute... Connections are precious resources and need to be opened, closed and disposed as quickly as possible. The connection must be open as long as the reader is engaged. So I moved updating the user interface (the text boxes) to outside the using block.
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
Dim String1 As String = ""
Dim String2 As String = ""
Using SQLcon As New SqlConnection("Your connection string"),
Command As New SqlCommand("Select * From tblProductsStocks WHERE productName= #producName", SQLcon)
'Check your database for the actual datatype and field size
Command.Parameters.Add("#productName", SqlDbType.VarChar, 100).Value = ComboBox2.SelectedItem.ToString
SQLcon.Open()
Dim SQLReader As SqlClient.SqlDataReader = Command.ExecuteReader()
SQLReader.Read()
String1 = SQLReader.Item("productType").ToString
String2 = SQLReader.Item("productMass").ToString
End Using 'closes and disposes the connection and command
TextBox1.Text = String1
TextBox2.Text = String2
End Sub

How to make connection VFP database with VB.NET

I'm creating a system that use foxpro as a database. I keep getting this error error [42S02][microsoft][ODBC visual foxpro driver] not a table when I want to connect VFP database with Visual Studio. When I add data connection in the visual studio, it shows connection success, but when I try to open the table, it shows the error.
This is a VB.Net system that use database foxpro 9. I have use mysql as the database and it work, but when I try to use foxpro database I get an error.
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class login
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim oConn = CreateObject("adodb.connection")
oConn.ConnectionString = "Provider=vfpoledb;DSN=visual_foxpro"
oConn.Open()
Dim conn = New OleDbConnection()
Dim cmdString As String = "SELECT * FROM `login` WHERE `staffID`= #staffid AND `staffName`= #staffname"
Dim cmd As New OleDbCommand(cmdString, oConn)
cmd.Parameters.Add(New OleDbParameter("staffID", CType(txtStaffID.Text, String)))
cmd.Parameters.Add(New OleDbParameter("staffName", CType(txtStaffID.Text, String)))
Dim adapter As New OleDbDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("Staff ID or Staff Name not available")
Else
MessageBox.Show("Welcome " & txtStaffName.Text)
Dim form As New formLeave
form.PassStaffid = txtStaffID.Text
form.PassStaffName = txtStaffName.Text
form.Show()
Me.Hide()
End If
End Sub
End Class
I expected the system can login using the database.
VFP database versions later than 6.x do not have an official ODBC driver from Microsoft. If you HAVE TO use ODBC, then you can find alternative drivers from sources like Sybase ADS. I use OLEDB instead successfully well.
While your code might work with MySQL, that is not the way you should write it. Also, it is MySQL specific, it wouldn't work in say MS SQL Server or postgreSQL either. You should read the documentation on the backend you are using. In VFP (or MS SQL Server, postgreSQL ...), you don't use back tics as table and field name identifiers. In VFP, if need be, to use name identifiers you could use single, double quotes or square brackets but you would need to enclose with parentheses (and use only for table name in an SQL query). Anyway, the easy way is to simply not to use identifiers at all.
Also, with an ODBC or OLEDB query, you need to use ? as parameter placeholders. Using #staffID wouldn't normally work in MySQL, ... either, but driver makers decided to support them for those backends.
From your messageBox messages, looks like you expect to get a single row for that query (I don't know why you use both staffId and staffName if staffId is primary key). Anyway here is your query in VB.Net:
Imports System.Data.OleDb
Public Class login
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim strConn As String = "Provider=VFPOLEDB;Data source=c:\MyDataFolder\"
Dim strQuery As String = <sql>SELECT *
FROM login
WHERE staffID=? AND staffName=?
</sql>
Using cn As New OleDbConnection(strConn)
Using cmd As New OleDbCommand(strQuery, cn)
cmd.Parameters.Add("#staffid", OleDbType.VarChar).Value = txtStaffID.Text;
cmd.Parameters.Add("#staffname", OleDbType.VarChar).Value = txtStaffName.Text;
cn.Open()
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
If rdr.Read()
MessageBox.Show("Welcome " & txtStaffName.Text)
Dim form As New formLeave
form.PassStaffid = txtStaffID.Text
form.PassStaffName = txtStaffName.Text
form.Show()
Me.Hide()
Else
MessageBox.Show("Staff ID or Staff Name not available")
End If
cn.Close()
End Using
End Using
End Sub
End Class

how to populate items from database in a listbox in vb.net

I was developing an application using oop concept.I have a class that has 2 attributes and have Get and Set methods namely WorkItemNumber and Description.
On the client side i have a list box used to populate the work items based on their description.Here's the code i wrote in the class o read items from the database.
Public Sub LoadWorkItem()
' Load the data.
' Select records.
Dim oWorkItem As WorkItem = New WorkItem()
Dim conn As New OleDbConnection
Dim data_reader As OleDbDataReader
conn = oWorkItem.GetDbConnection()
Dim cmd As New OleDbCommand("SELECT * FROM work_item ORDER BY [work item number]", conn)
data_reader = cmd.ExecuteReader()
'ListBox1.Items.Clear()
If data_reader.HasRows = True Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
Loop
End If
data_reader.Close()
data_reader = Nothing
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
End Sub
How do i populate the listbox using the code,and if there's any improvement on the code please do tell me as well.Thank you
To poulate your ListBox, do this...
ListBox1.Item.Clear()
If data_reader.HasRows Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
ListBox1.Items.Add(New ListItem(Description, WorkItemNumber)
Loop
End If
As far as improvements, start by using a Using statement for the DB connection. In your code, if there is an exception while the database connection is open, it will never get closed. This is better...
Using conn As OleDbConnection = oWorkItem.GetDbConnection()
' Execute SQL and populate list...
End Using
The above code assures that your connection will be closed.
Then, turn on Option Strict and Option Explicit. This will force you to declare the Type for Description and WorkItemNumber and cast them as Strings when adding a ListItem. This will reduce run-time errors.
Finally, if this is anything but a small app you are doing as a learning experiment, you should read up on tiered application design. Your code is mixing UI, business logic, and data access in the same method. This is generally frowned upon.
Your "user interface" LoadWorkItem() method should ask a "core" method for a list of WorkItems.
Your core method should then ask a "data access" method for data.
The "data access" method should make the call to the database.
Happy coding.
Update: You can find excellent info about n-Tier architecture on MSDN. A good book to read once you grasp the fundamentals and have some confidence in .NET is Visual Basic .NET Business Objects.
Imports System.Data.SqlClient 'Reference The Sql Client
Public Class Form1
''Make sure to change the connection string below to your connection string this code only works for SQL DataBase. If Your connection String is wrong This will Not Work
Dim connString As String = "Data
Source=NameofYourSQLServer\SQLEXPRESS;Initial Catalog=NameOfYourDataBase;Integrated Security=True"
Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oCon = New SqlConnection
oCon.ConnectionString = connString
dsDIV = New DataSet
' Select all Fields and order by ID or Replace * with name of Field
daDIV = New SqlDataAdapter("SELECT * FROM NameOfYourTable ORDER BY Id DESC", oCon)
'*** Define command builder to generate the necessary SQL
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
Try
daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
daDIV.Fill(dsDIV, "DIV")
tblDIV = dsDIV.Tables("DIV")
ListBox1.DataSource = tblDIV
ListBox1.DisplayMember = "NameOfTheFieldYouWanttoDisplay"
Catch ex As Exception
MsgBox("Encountered an Error;" & vbNewLine & ex.Message)
oCon.Close()
End Try
End Sub

Vb.net 2010 Connection to SQL Server 2008

I am trying to connection to MS SQL SERVER 2008 database (students), i want to make sure:
1) If connection string that i made is OK
Dim connectionString As New SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
2) How can i check if dataset is producing any results?
Code:
Public Class Form1
'Connection String + DataAdaptor + DataSet
'Declared Outside Any Subroutines/Functions
Dim connectionString As New SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
Dim dataAdaptor As New SqlDataAdapter()
Dim objdataSet As New DataSet()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dataAdaptor.SelectCommand = New SqlCommand()
dataAdaptor.SelectCommand.Connection = connectionString
dataAdaptor.SelectCommand.CommandText = "select * from basic_info;"
dataAdaptor.SelectCommand.CommandType = CommandType.Text
connectionString.Open()
dataAdaptor.Fill(objdataSet, "StudentInfo")
connectionString.Close()
grd.AutoGenerateColumns = True
grd.DataSource = objdataSet
grd.DataMember = "basic_info"
dataAdaptor = Nothing
connectionString = Nothing
End Sub
About your first question, If connection string that i made is OK
If you did not get any exceptions, you've successfully made the connection to your database.
About your second question.
There are two things you can do.
Debug the wrong way. (It works though)
MsgBox(objdataSet.Tables[0].Rows.Count);
Learn and debug the correct way.
Read these articles
Debugging Basics
Visual Studio Debugging
Debugging Basics: Breakpoints
Anyway, learn how to use the debugger properly, put a break point, analyse the objdataSet object in a watch window and see if any results are present.
1) If connection string that i made is OK
Easy way to verify connection strings is to connect using the "Server Explorer" in Visual Studio. Once you get a good connection, right-click on the connection and just grab the "Connection String" property.
2) How can i check if dataset is producing any results?
MsgBox(objdataSet.GetXML)
GetXML will return ALL the data in the dataset in XML format.
Also, don't globally declare variables if you don't need to.
Declare them closer, or not at all, like so...
Dim objdataSet As New Data.DataSet()
Using connectionString As New Data.SqlClient.SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
With New Data.SqlClient.SqlDataAdapter()
.SelectCommand = connectionString.CreateCommand
.SelectCommand.CommandText = "select * from basic_info;"
.SelectCommand.CommandType = Data.CommandType.Text
.Fill(objdataSet, "StudentInfo")
End With
MsgBox(objdataSet.GetXML)
End Using
'Now put it in your dataset...'
Hope this helps.