Visual Basic .NET连接到sql server compact 3.5

时间:2009-11-24 01:35:51

标签: sql-server vb.net

我是Microsoft Visual Studio 2008的初学者用户,我想问一下将Visual Basic 2008表单连接到SQL Server compact 3.5的初始代码是什么。我想使用上述应用程序创建一个新的帐户程序。

1 个答案:

答案 0 :(得分:0)

查看connectionstrings.com的连接字符串。

我的一些示例代码包含在下面。为清楚起见,删除了无关的内容和注释。它在C#中,但有很多工具可以将它转换为VB。或者您可以通过自己手动转换来学习另一个版本; - )

GetAllEmployees将返回Employees列表。然后可以根据需要对列表进行处理/绑定。

 public static SqlConnection GetConnection()
        {
            //TODO: Use connectionString from app.config file
            string connString = "Data Source=.\\SQLEXPRESS2008;Initial Catalog=Northwind;Integrated Security=True";

            SqlConnection conn = new SqlConnection(connString);
            return conn;
        }


public static List<Employee> GetAllEmployees()
{
    SqlConnection conn = DA.GetConnection();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT * FROM Employees";

    return CreateEmployeeList(cmd);
}




private static List<Employee> CreateEmployeeList(SqlCommand cmd)
{
    List<Employee> employees = new List<Employee>();

    using (cmd)
    {
        cmd.Connection.Open();

        SqlDataReader sqlreader = cmd.ExecuteReader();

        while (sqlreader.Read())
        {
            Employee employee = new Employee
                {
                    FirstName = sqlreader["FirstName"].ToString(),
                    LastName = sqlreader["LastName"].ToString(),
                    StreetAddress1 = sqlreader["Address"].ToString(),
                    City = sqlreader["City"].ToString(),
                    Region = sqlreader["Region"].ToString(),
                    PostalCode = sqlreader["PostalCode"].ToString()
                };

            employees.Add(employee);
        }
        cmd.Connection.Close();
    }
    return employees;
}