无法从C#表单应用程序连接到本地DB(mdf)

时间:2015-06-19 15:00:37

标签: c# sql database forms local

我尝试使用数据库创建和查询。为了做到这一点,我启动了一个C#表单应用程序,添加了一个数据库服务,然后添加了一个带有一些值的表,然后我想使用一些代码来检索这些值。 这是代码:

string conn = "data source = ./SQLEXPRESS; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlConnection sql = new SqlConnection(conn);

sql.Open();
MessageBox.Show("Connection Opened");
sql.Close();

可悲的是,该程序在打开时抛出异常,因为它似乎无法找到数据库......

"找不到服务器或无法访问服务器"

我不知道问题是什么,你会建议什么?

好的,它现在似乎有效,但我的查询语法不正确

string conn =" Server =(LocalDB)\ v11.0; AttachDbFilename = C:\用户\华硕\桌面\ RobaMia \ SQLSERVER \ WindowsFormsApplication3 \ WindowsFormsApplication3 \ Database1.mdf; Integrated Security = True; Connect Timeout = 30; User Instance = False&#34 ;;

        string queryString = "SELECT * FROM Table";
        SqlConnection sql = new SqlConnection(conn);

        sql.Open();
        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlCommand command = new SqlCommand(queryString, sql);

      /* --->here I get the error*/ command.ExecuteNonQuery();

        DataSet data = new DataSet();
        adapter.Fill(data);
        MessageBox.Show(data.ToString());
        sql.Close();

2 个答案:

答案 0 :(得分:2)

看起来您的连接字符串错误的数据源部分。它应该是:

"Data source=.\\SQLEXpress"

达成:

string conn = "Data source=.\\SQLEXpress; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";

https://www.connectionstrings.com/sql-server/

作为补充说明,您可能最好将其放在app.configweb.config文件中,只需要多次引用连接字符串,然后再决定更改它的值。< / p>

答案 1 :(得分:0)

您是否尝试过(LocalDB)而不是SQLExpress?

"Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;"

http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string