以编程方式创建SQLCE数据库

时间:2011-06-01 04:27:19

标签: c# sql-server-ce

[已编辑 - 有回答]

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

/* 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();
        }

    }
}

1 个答案:

答案 0 :(得分:30)

我使用过SQLCE 3.1和SharpDevelop,试试这段代码,看看这是不是你想要的:

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();
}

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