简体   繁体   中英

C# Connect to a SQL server CE programmatically

I'm completely new to database programming. I'm working with Visual Studio 2010 and want to create a database programmatically.

So far I've tried to connect to a SQL Server Compact Edition like this:

public class HistoryDBAccess
{
    private SqlConnection conn = new SqlConnection();

    public HistoryDBAccess()
    {
        conn.ConnectionString = @"Server=localhost;Integrated security=SSPI;database=master";
        string str = "CREATE DATABASE MyDatabase ON PRIMARY " +
            "(NAME = MyDatabase_Data, " +
            "FILENAME = 'C:\\MyDatabaseData.mdf', " +
            "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
            "LOG ON (NAME = MyDatabase_Log, " +
            "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
            "SIZE = 1MB, " +
            "MAXSIZE = 5MB, " +
            "FILEGROWTH = 10%)";

        SqlCommand myCommand = new SqlCommand(str, conn);
        try
        {
            conn.Open();
            myCommand.ExecuteNonQuery();
            MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }

    }
}

The connection in the Ctor fails with the message that a connection could not be established.

Using the database wizard with VS2010 is fine, but how I can see the SQLCe server under windows 7?

Is it somewhere under the control panel and do I need a default password in the connection string?

Many thanks,

Juergen

我认为您应该使用服务器资源管理器(或数据库资源管理器)在您的项目中向数据库添加连接,然后检查连接字符串。

It looks like you are trying to pass the con object before opening the connection.

So Try this and let me know.

 public HistoryDBAccess()
    {
        conn.ConnectionString = @"Server=localhost;Integrated security=SSPI;database=master";
        string str = "CREATE DATABASE MyDatabase ON PRIMARY " +
            "(NAME = MyDatabase_Data, " +
            "FILENAME = 'C:\\MyDatabaseData.mdf', " +
            "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
            "LOG ON (NAME = MyDatabase_Log, " +
            "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
            "SIZE = 1MB, " +
            "MAXSIZE = 5MB, " +
            "FILEGROWTH = 10%)";
          conn.Open();

        SqlCommand myCommand = new SqlCommand(str, conn);
        try
        {

            myCommand.ExecuteNonQuery();
            MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }

    }
}

Once you create it, you're probably going to want to interact with it. You should consider using NHibernate. It has a feature called SchemaExport that can drop and create databases as much as you like.

Here's an example using SQL Express, but it's not much different to use Compact Edition. You can get NHibernate installed in your project by opening it in Visual Studio and clicking Project > Manage NuGet Packages, then searching All Online for NHibernate.

public class NHContext
{
    protected static Configuration NHConfiguration;
    protected static ISessionFactory SessionFactory;

    public static void DropDatabase()
    {
        new SchemaExport(NHConfiguration).Drop(false, true);
    }

    public static void CreateDatabase()
    {
        new SchemaExport(NHConfiguration).Create(false, true);
    }

    protected static Configuration configureNHibernate()
    {
        var configure = new Configuration();
        configure.SessionFactoryName("BuildIt");

        configure.DataBaseIntegration(db =>
        {
            db.Dialect<MsSql2008Dialect>();
            db.Driver<Sql2008ClientDriver>();//db.Driver<SqlClientDriver>();
            db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            db.IsolationLevel = IsolationLevel.ReadCommitted;
            db.ConnectionString = @"Data Source=.\SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=NHibernate32Test;User Instance=False";
            db.Timeout = 10;

            // For testing
            db.LogFormattedSql = true;
            db.LogSqlInConsole = true;
            db.AutoCommentSql = true;
        });

        return configure;
    }

    public static void Setup()
    {
        NHConfiguration = configureNHibernate();
        HbmMapping mapping = getMappings();
        NHConfiguration.AddDeserializedMapping(mapping, "NHibernate32Test");
        SchemaMetadataUpdater.QuoteTableAndColumns(NHConfiguration);
        SessionFactory = NHConfiguration.BuildSessionFactory();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM