Creating a database with Code
Question: My company is in the process of writing a Windows Mobile 5 application. The application will make use of a locally created database that is built in the application after the user answers some questions. Essentially, based on the answers they provide we create the database with code. Do you have any idea how this can be done?
Answer: Sure, using SQL Server Mobile 2005 you can create a database with code using the following steps.
- Set the following references
2. Place the following code in your form. For this example, I placed the code in a button.
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
If Not File.Exists("Contacts.sdf") Then
' create the database
Dim lvarEngine As SqlCeEngine = New SqlCeEngine("Data Source=contacts.sdf")
lvarEngine.CreateDatabase()
End If
' connect to the database
Dim conn As SqlCeConnection = New SqlCeConnection("Data Source=contacts.sdf")
conn.Open()
' create the table
Dim cmd As New SqlCeCommand
cmd.Connection = conn
' create the table
cmd.CommandText = "CREATE TABLE Contact(custID int PRIMARY KEY, custname ntext, custbalance money)"
cmd.ExecuteNonQuery()
' populate the data
cmd.CommandText = "INSERT INTO Contact(custid, custname, custbalance) VALUES (0, 'Thom Robbins', 1434.12)"
cmd.ExecuteNonQuery()
End Sub
When the application is run the database can be seen on the device with the Query Analyzer as shown below.
Comments
- Anonymous
August 20, 2006
Question: My company is in the process of writing a Windows Mobile 5 application. The application will...