C# 如何将数据库附加到安装程序

C# 如何将数据库附加到安装程序,c#,asp.net,winforms,visual-studio,visual-studio-2015,C#,Asp.net,Winforms,Visual Studio,Visual Studio 2015,这是我的第一个带有数据库的应用程序。它在我的电脑上安装并运行得很好。但当安装在另一台电脑上时,它会抛出一个错误: System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not acces

这是我的第一个带有数据库的应用程序。它在我的电脑上安装并运行得很好。但当安装在另一台电脑上时,它会抛出一个错误:

System.Data.SqlClient.SqlException (0x80131904): A network-related or 
instance-specific error occurred while establishing a connection to SQL 
Server. The server was not found or was not accessible. Verify that the 
instance name is correct and that SQL Server is configured to allow remote 
connections. (provider: SQL Network Interfaces, error: 50 - Local Database 
Runtime error occurred. The specified LocalDB instance does not exist.
我需要的是,安装文件必须在本地自包含一个数据库,以便我可以存储一些数据并检索它

示例应用程序如下所示:

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace form1
{
   public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }
    SqlDataAdapter da;
    DataSet ds;
    SqlConnection con;
    private void button1_Click(object sender, EventArgs e)
    {
        con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\sql.mdf;Integrated Security=True");
        da = new SqlDataAdapter("insert into STUDENTDATA(STUDENT,CLASS,SEX)values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')", con);
        ds = new DataSet();
        da.Fill(ds);
        MessageBox.Show("Registration has been successful");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();

    }
  }
}

注意:另一台计算机中安装了Visual Studio。

试试这个,它对我有用

转到工具/选项/数据库工具/单击数据连接/现在从右侧框中删除Sql Server实例名称/单击确定

然后尝试添加另一个数据库:打开解决方案资源管理器/右键单击项目/添加新项目/选择基于服务的数据库/单击添加


在数据库服务器上安装Visual Studio与此无关。如果您要学习数据访问,请确保了解。将数据连接存储为字段是一种糟糕的做法。你应该尽可能限制他们的活动范围。无论如何,您是否已验证要部署到的计算机上安装了SQL Server LocalDB?SQL Server LocalDB已安装在该计算机上。我已通过命令行检查了它
sqllocaldb I
。实例是V11.0。是否验证了数据库文件位于正确的位置?它位于项目文件夹中。如果将
|DataDirectory | \\sql.mdf
替换为文件所在的物理硬编码路径,会发生什么情况?