VB.NET+SQLCE操作数据库简单例子

在VS.NET 2005中,使用VB开发PPC程序,可以很容易加入使用SQLCE的功能。
基本步骤如下:
(1)使用VB.net建立一个智能设备应用程序,平台选择application device;
(2)右键点击“解决方案”该工程下面的“引用”,然后选择“添加引用”,然后添加“System.Data.SqlServerCe”;
(3)在需要使用SQLCE的窗体代码中添加两个引用
Imports System.Data.SqlServerCe
Imports System.IO

经过这些操作,就可以使用SQLCE了。

定义两个全局变量
'数据库连接以及结果集变量
    Dim conn As New SqlCeConnection("Data Source=\My Do***ents\Phone.sdf")
    Dim ds As DataSet

余下的就是使用SQL进行数据库操作

'创建数据库
    Sub CreateDB()
        If Not File.Exists("\My Do***ents\Phone.sdf") Then
            Dim sqlEngine As New SqlCeEngine("Data Source = \My Do***ents\Phone.sdf")
            sqlEngine.CreateDatabase()

            Dim cmd As New SqlCeCommand("CREATE TABLE Phone(Name nvarchar(20) Primary Key NOT NULL,Number nvarchar(20))", conn)

            conn.Open()
            cmd.ExecuteNonQuery()
           
            conn.Close()

            status = status + "创建数据库成功!" & vbCrLf
        Else
            status = status + "数据库已经存在!" & vbCrLf
        End If
    End Sub

    '添加数据
    Sub AddData()
        If File.Exists("\My Do***ents\Phone.sdf") Then

            Dim cmd As New SqlCeCommand("", conn)

            conn.Open()

            cmd.CommandText = "INSERT INTO Phone(Name,Number) VALUES ('abcde','12345')"
            cmd.ExecuteNonQuery()
            cmd.CommandText = "INSERT INTO Phone(Name,Number) VALUES ('bcdef','23456')"
            cmd.ExecuteNonQuery()

            conn.Close()

            status = status + "添加记录成功!" & vbCrLf
        Else
            status = status + "数据库尚未创建!" & vbCrLf
        End If
    End Sub

    '显示数据库中的数据
    Sub List()
        If File.Exists("\My Do***ents\Phone.sdf") Then

            conn.Open()
            Dim reader As SqlCeDataReader
            Dim cmd As New SqlCeCommand("SELECT * FROM Phone", conn)
            reader = cmd.ExecuteReader
            While reader.Read

                status += "姓名:" & reader.Item("Name") & "  电话:" & reader.Item("Number") & vbCrLf

            End While
            conn.Close()
        Else
            status = status + "数据库尚未创建!" & vbCrLf
        End If
    End Sub

    '删除数据库的数据
    Sub DeleteData()
        If File.Exists("\My Do***ents\Phone.sdf") Then

            conn.Open()

            Dim cmd As New SqlCeCommand("DELETE FROM Phone", conn)
            cmd.ExecuteNonQuery()

            conn.Close()

            status = status + "数据库的记录已经删除!" & vbCrLf
        Else
            status = status + "数据库尚未创建!" & vbCrLf
        End If
    End Sub

    '修改数据库的数据
    Sub ModifyData()
        If File.Exists("\My Do***ents\Phone.sdf") Then

            conn.Open()

            Dim cmd As New SqlCeCommand("UPDATE Phone SET Name='Hello', Number='87654321' WHERE Name='abcde' AND Number='12345'", conn)
            cmd.ExecuteNonQuery()

            conn.Close()

            status = status + "数据库的记录已经修改!" & vbCrLf
        Else
            status = status + "数据库尚未创建!" & vbCrLf
        End If
    End Sub

你可能感兴趣的:(WINCE)