February17
SQL Compact Database is often used on individual computers, often bundled with personal software. This database does not involve setting up server and usually is used for mobile applications. I would like to share with you the ways and codes to connect to SQL Compact Database using VB.NET.
1. Add the data source to your application. The SQL Compact database file ends with *.sdf. You can create this database through either Visual Studio or Microsoft SQL Server Express. Declare the connection string in the public class:
Dim DBconnectionString As String = “Data Source=|DataDirectory|\databasename.sdf”
2. Then, put this code when you want to connect to the database
Dim cmd As New SqlCeCommand
Dim conn As New SqlCeConnection(DBconnectionString)
Dim cmdGetName As New SqlCeCommand
Dim daGetName As New SqlCeDataAdapter
Dim dsGetName As New DataSet
Dim dtGetName As New DataTable
Try
cmd.Connection = conn
conn.Open()
cmdGetFencersName = conn.CreateCommand
cmdGetFencersName.CommandText = “Put your command here”
daGetName.SelectCommand = cmdGetName
daGetName.Fill(dsGetName, “TableName”)
dtGetName = dsGetName.Tables(”TableName”)
‘Now, decide how you want to display the data.
‘The following code shows you how to add the data from the data table to a combobox.
Dim i As Integer
For i = 0 To dtGetName.Rows.Count - 1
cmbName.Items.Add(dtGetName.Rows(i).Item(0))
Next
cmbName.Sorted = True
Catch ex As Exception
MsgBox(”Error: ” & ex.Source & “: ” & ex.Message, MsgBoxStyle.OkOnly, “There is a connection error with the database. Please Check.”)
End Try
conn.Close()
I hope that helps! =)