C# - 无法使用 SQLServer 连接到我的本地数据库



我是C#的新手,我正在尝试将我的应用程序连接到DB,所以我尝试了:

public ActionResult ConnexionBD(){
        SqlConnection cnx;
        cnx = new SqlConnection("Data Source=C:\Users\Antoine\Documents\Visual Studio 2012\Projects\Application\Application\App_Data\Database1.sdf;Initial Catalog=tstado;Integrated Security=True;Pooling=False");
        cnx.Open();
        SqlCommand cmd;
        cmd = new SqlCommand();
        cmd.CommandText="INSERT INTO Objet VALUES(1,'F',"+DateTime.Now+",'Moi')";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = cnx;
        cmd = new SqlCommand();
        cmd.CommandText = "SELECT * FROM Objet";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = cnx;
        SqlDataReader r;
        r = cmd.ExecuteReader();
        String chaine="";
        while (r.Read())
        {
            string nom = (string)r["Nom"];
            string date = (string)r["Date"];
            string user = (string)r["User"];
            chaine+=nom+"t"+date+"t"+user+"n";
        }
        cnx.Close();
        return View(chaine);
    }

它在第4行中断: cnx.open(); 。该错误说,由于网络,网络是无法理解的或无法访问的。(法语中的确切错误:" une erreuriurliéeAuréseauouspécifiquiqueàl'l'sests'est s'est produite lors del'établesmentd'une connexion - sql Server。de l'sest est recters et que sql server estconfiguré倒入自动载体connexions distantes。")

英语翻译;

当与网络或实例特异性有关的错误发生时 建立与SQL Server的连接。没有找到服务器或 无法访问。验证实例名称是正确的,并且 SQL Server配置为允许远程连接

我认为字符串连接可能是错误的,但我不确定。

如果有人可以帮助我..!

由于您使用的是本地数据库(.sdf),因此您需要参考system.data.data.sqlserverce(在添加参考>扩展程序中找到)并相应地更改代码(请参见下文)。

public ActionResult ConnexionBD()
    {
        SqlCeConnection cnx = new SqlCeConnection(@"Data Source=C:UsersAntoineDocumentsVisual Studio 2012ProjectsApplicationApplicationApp_DataDatabase1.sdf");
        cnx.Open();
        SqlCeCommand cmd = new SqlCeCommand
        {
            CommandText = "INSERT INTO Objet VALUES(1,'F'," + DateTime.Now + ",'Moi'",
            CommandType = CommandType.Text,
            Connection = cnx
        };
        cmd = new SqlCeCommand {CommandText = "SELECT * FROM Objet", CommandType = CommandType.Text, Connection = cnx};
        SqlCeDataReader r = cmd.ExecuteReader();
        String chaine = "";
        while (r.Read())
        {
            string nom = (string)r["Nom"];
            string date = (string)r["Date"];
            string user = (string)r["User"];
            chaine += nom + "t" + date + "t" + user + "n";
        }
        cnx.Close();
        return View(chaine);
    }

在您的解决方案资源管理器中,您应该将数据库文件的属性"复制到输出目录"标记为"始终"(或"如果您的需求",请始终",因此将其复制到您的bin您的调试器可以访问的文件夹。在您的连接字符串中,您将不得不只放置Database1.sdf

最新更新