简体   繁体   English

连接到C#中的数据库

[英]Connecting to a database in C#

I feel like an absolute idiot. 我觉得自己是个白痴。 I've been trying to connect to a database I created for a few hours now and I can't seem to get it to connect. 我一直在尝试连接到我现在创建的数据库几个小时,但似乎无法连接它。 Here is my code. 这是我的代码。

string chooseMoodCmbBx = moodCmbBx.SelectedIndex.ToString();
        string source = "Data Source='E:\\Documents\\Database\\MyDatabase.sdf';" +
                        "Password='password';" +
                        "Persist Security Info=False;";
        SqlConnection conn = new SqlConnection(source);
        try
        {
            conn.Open();
            MessageBox.Show("Succesfully Connected");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.ToString());
        }

You have an SDF file, meaning that you connect to a Sql Compact not to Sql Server. 您有一个SDF文件,这意味着您连接到Sql Compact而不是Sql Server。 You need to use the classes in the namespace System.Data.SqlServerCe 您需要使用名称空间System.Data.SqlServerCe的类

SqlCeConnection conn = new SqlCeConnection(source);

Also, I am not sure of this, but I think you don't need to have single quotes around values in the connection string 另外,我不确定这一点,但我认为您不需要在连接字符串中的值周围使用单引号

    string source = "Data Source=E:\\Documents\\Database\\MyDatabase.sdf;" +
                    "Password=password;" +
                    "Persist Security Info=False;";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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