I am trying to learn SQLLite (Years of Experience with apps using SQL Server). I am going slowly and right off the bat I could not open a connection to a database created in SQLite Studio. I have tried a number of different examples with no luck. I first tried with a Nuget package and then went to the SQLite website and downloaded the 64-bit binaries for .Net 4.5. I get this error no matter what I try: system.BadImageFormatException.
Can someone please tell me what I'm doing wrong or point me to an example that really works?
Thanks!!!
Imports System.Data.SQLite
Public Class Form1
Private connectionstring As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim exePath As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
Dim dbPath As String = exePath & "\NamesTest.db"
connectionstring = "Data Source=" & dbPath
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLiteConn As New SQLiteConnection(connectionstring)
SQLiteConn.Open()
End Sub
End Class
Related
With my VBA experience I´m trying VB.NET now. First I need a connection to my MS SQL Server.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=MyDS;Initial Catalog=MyIC;User ID=MyUser;Password=MyPW"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
The error: Type "SqlConnection" is not defined.
SqlConnection is also red underlined directly in the Dim cnn - line.
Also there is no intellisense suggestion for it.
I came across System.Data.dll several times on google searches. Is it missing in my system? I tried to import it without success.
Then I searched it in
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5
and
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0
It isn´t there.
Is System.Data.dll my problem?
Win10, Visual Studio Version 17.4.1 (64-Bit)
Maybe I´ve installed Visual Studio incomplete? Or is there an other reason for my problem?
Thank you very much for your time and a hot tip :-)
So I have been able to connect my database to VB forms, and I am also able to see the table and the fields within. But I can't figure how to make the data appear in the table because it's just blank.
I do have some data stores in the actual access database but it won't show up in my program.
Is there a particular code I need to write? This is what I have so far. The database is called the 'POS system'.
Private Sub OrdersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles OrdersBindingNavigatorSaveItem.Click
Me.Validate()
Me.OrdersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.POS_systemDataSet)
End Sub
It is usually a good idea to separate your database code from your user interface code. Create a connection and a command in a Using block so they will be closed and disposed at End Using. Pass the connection string to the constructor of the connection. Pass the CommandText and connection to the constructor of the command. Open the connection and execute the command returning a DataReader to load the DataTable.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetData()
DataGridView1.DataSource = dt
End Sub
Private Function GetData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Select * From SomeTable;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
When I enter the fields it works and sends the records to the database and if I clear the form and enter another it also sends that one to the database but when I stop debugging, the database is empty.
Is there something wrong with my code?
What should I do to resolve this issue?
• I am using VB.NET with a Microsoft Access database
• There are two pages of code: Control and Create Account Form
Control
Imports System.Data.OleDb
Public Class DBControl
'CREATE YOUR DB CONNECTION
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=Hotel.mdb;")
'PREPARE DB COMMAND
Private DBCmd As OleDbCommand
'DB DATA
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'QUERY PARAMETERS
Public Params As New List(Of OleDbParameter)
'QUERY STATISTICS
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'RESET QUERY STATS
RecordCount = 0
Exception = ""
Try
'OPEN A CONNECTION
DBCon.Open()
'CREATE DB COMMAND
DBCmd = New OleDbCommand(Query, DBCon)
'LOAD PARAMS INTO DB COMMAND
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
'CLEAR PARAMS LIST
Params.Clear()
'EXECUTE COMMAND & FILL DATABASE
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
'CLOSE YOUR CONNECTION
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
'INCLUDE QUERY & COMMAND PARAMETERS
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Create Account Form
Imports System.Data.OleDb
Public Class Create
Private Access As New DBControl
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=Hotel.mdb")
Private Sub Create_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
AddUser()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
txtForename.Clear()
txtSurname.Clear()
txtNumber.Clear()
txtEmail.Clear()
txtPass.Clear()
txtCity.Clear()
End Sub
Private Sub cbxTitle_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxTitle.SelectedIndexChanged, txtFirst.TextChanged, txtSurname.TextChanged, txtEmail.TextChanged, txtPass.TextChanged
If Not String.IsNullOrWhiteSpace(cbxTitle.Text) AndAlso Not String.IsNullOrWhiteSpace(txtFirst.Text) AndAlso Not String.IsNullOrWhiteSpace(txtSurname.Text) AndAlso Not String.IsNullOrWhiteSpace(txtEmail.Text) AndAlso txtPass.Text.Length = 8 Then
btnCreate.Enabled = True
End If
End Sub
Private Sub AddUser()
'ADD PARAMETERS
Access.AddParam("#Title", cbxTitle.Text)
Access.AddParam("#Forename", txtForename.Text)
Access.AddParam("#Surname", txtSurname.Text)
Access.AddParam("#Number", txtNumber.Text)
Access.AddParam("#Email", txtEmail.Text)
Access.AddParam("#Pass", txtPass.Text)
Access.AddParam("#City", txtCity.Text)
'EXECUTE INSERT COMMAND
Access.ExecQuery("INSERT INTO Customers([Title], [Forename], [Surname], [Number], [Email], [Pass], [City])" &
"VALUES(#Title, #Forename, #Surname, #Number, #Email, #Pass, #City)")
'REPORT & ABORT ON ERRORS
If Not String.IsNullOrEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
DBCon.Close()
End Sub
End Class
Any help is appreciated
Thank you in advance :)
There is a proper way to work with file-based databases in VB.NET.
Add the data file to your project in the Solution Explorer. If you're prompted to copy the file into the project, accept.
Set the Copy To Output Directory property of the data file to Copy If Newer.
Use "|DataDirectory|" to represent the folder path of the data file in your connection string, e.g. Dim connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Hotel.mdb;".
Now you have two copies of your database. You have the one in the project folder, with the other source files, and the one in the output folder, with the EXE. The source file should stay clean, unsullied by test data. The copy in the output folder is the one you connect to when you debug so that's the one you need to look in to find any changes you make while debugging/testing.
Because you set it to only copy when the source file is newer than the output file, any changes you make while testing will not be lost unless you actually make a change to the source file, e.g. add a column or a table. By default, that property is set to Copy Always, which means that your source file is copied over the output file every time the project is built, so any time any source file changes and you run the project again. That's why your data "disappears".
In my application I want the show the SQL Query progress. For example, assume a user clicked on a backup button, then I want him to be able to view the progress of the query he made in case the database is too big to restore or backup. At first I tried to do this by assuming how much disk space the database might take before even start backing up and then using that with the copying rate to estimate a time it might take to backup. But unfortunately I failed. Then by luck I found one lovely T-SQL command that show the stats when used in SSMS and it is just using an extra line 'With Stats = [Some integer] e.g. 1, 10, 20, etc' but here is the problem. I cannot find any work through for this to work with Vb.Net aka my application.
I found this awesome query from this link (www.mssqltips.com). If you open the website you can see few examples showing this.
The code to get stats:
Use dbName Backup dbName To Disk='BackupLocation' With STATS = 10
Edit #1:
Adding these lined of code now does showing the InfoMessage I was searching for but still not useful as this shows up only when the full operation is completed.
But what I want is to show them dynamically.
Code that worked:
AddHandler con.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
Private Sub OnInfoMessage(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlInfoMessageEventArgs)
strInfo.AppendLine(e.Message)
txtMsg.Text = strInfo.ToString
End Sub
My complete code:
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Text
Public Class BackupForm
Dim ConnectionString As String = My.Settings.LADBConnectionString
Dim con As SqlConnection = New SqlConnection(ConnectionString)
Dim cmd As New SqlCommand()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Using OFD As New SaveFileDialog
With OFD
.FileName = "Backup " + Now.ToString("dd-MM-yyyy")
.Filter = "Log Application Backup |*.bak"
.CheckFileExists = False
.OverwritePrompt = False
Select Case .ShowDialog
Case DialogResult.OK
If .FileName <> "" Then
txtBackup.Text = .FileName
End If
End Select
End With
End Using
End Sub
Private Sub btnBackup_Click(sender As Object, e As EventArgs) Handles btnBackup.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Dim strInfo As New StringBuilder
Private Sub OnInfoMessage(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlInfoMessageEventArgs)
strInfo.AppendLine(e.Message)
txtMsg.Text = strInfo.ToString
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim backupQuery As String = $"use LDDB Backup database LDDB to Disk='{txtBackup.Text}' With STATS = 1"
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = backupQuery
cmd.Connection = con
AddHandler con.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
con.Close()
con.Dispose()
End Try
End Sub
Private Sub BackupForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class
This is my first post on stackoverflow so please hang with me. I am attempting to update an access database using VB.NET. Using the following series of videos (starting with this one), we have been able to properly use our form to save new data into the access database.
https://www.youtube.com/results?search_query=vb.net+ms+access+database+tutorial+1+%23+add+new+remove+save+data+in+database+using+vb.net
However, when we start up the form again after opening up access to make sure the updates have occurred (which they always do), none of our changes are there. And when we open up access again the changes we made that showed up in the access database are gone, and the access database goes back to its original state (the state it was when we linked it to visual studio in the first place).
Below is the code we have so far, we appreciate any help you can give us!
Thanks.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Sheet1BindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles Sheet1BindingNavigatorSaveItem.Click
Me.Validate()
Me.Sheet1BindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(MIS275_Small_BusinessDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MIS275_Small_BusinessDataSet.Sheet1' table. You can move, or remove it, as needed.
Timer1.Start()
Me.Sheet1TableAdapter.Fill(MIS275_Small_BusinessDataSet.Sheet1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Sheet1BindingSource.AddNew()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Save.Click
Try
Sheet1BindingSource.EndEdit()
Sheet1TableAdapter.Update(MIS275_Small_BusinessDataSet.Sheet1)
MessageBox.Show("Data Saved")
Catch ex As Exception
MessageBox.Show("Error")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim count As Integer
count = Sheet1BindingSource.Count
End Sub
End Class