以编程方式创建SQLCE数据库 [英] Create SQLCE database programmatically

查看:61
本文介绍了以编程方式创建SQLCE数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我以编程方式创建SQL CE数据库的代码:

Following is my code to create SQL CE database programmatically:

/* get the Path */
var directoryName = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var fileName = System.IO.Path.Combine(directoryName, "Foo2Database.sdf");

/* check if exists */
if (File.Exists(fileName))
    File.Delete(fileName);

string connStr = @"Data Source = " + fileName;

/* create Database */
SqlCeEngine engine = new SqlCeEngine(connStr);
engine.CreateDatabase();

/* create table and columns */
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
    using (SqlCeCommand cmd = new SqlCeCommand(@"CREATE TABLE FooTable (Foo_ID int, FooData NVARCHAR(200))", conn))
    {
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            conn.Close();
        }

    }
}


推荐答案

我使用过SQLCE 3.1和SharpDevelop,请尝试下面的代码,看看这是否是您想要的:

I have worked with SQLCE 3.1 and SharpDevelop, Try this code and see if this is what you want:

string connStr = "Data Source = FooDatabase.sdf; Password = SomePassword";

if (File.Exists("FooDatabase.sdf")) 
    File.Delete("FooDatabase.sdf");  

SqlCeEngine engine = new SqlCeEngine(connStr); 
engine.CreateDatabase();

SqlCeConnection conn = null;


try 
{
    conn = new SqlCeConnection(connStr);
    conn.Open();

    SqlCeCommand cmd = conn.CreateCommand();
    cmd.CommandText = "CREATE TABLE FooTable(col1 int, col2 ntext)";
    cmd.ExecuteNonQuery();
}
catch 
{

}
finally 
{
    conn.Close();
}

请注意,数据库只是一个文件,因此您可以检查数据库是否通过查看文件是否存在来存在,也可以通过删除文件来删除数据库。希望这会有所帮助。

Note that the database is just a file, so you can check if the database exists by looking if the file exists, also you can delete the database by deleting the file. Hope this helps.

这篇关于以编程方式创建SQLCE数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆