简体   繁体   English

C#MDF本地数据库

[英]C# mdf local database

I googled for half a day how to set the path of my database so if I put it on an other computer it will work. 我用半天时间搜索了如何设置数据库的路径,因此,如果将其放在另一台计算机上,它将可以正常工作。 I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours. 我会继续使用谷歌搜索功能,但是我真的非常需要答案...我将在几个小时内将其用于比赛。

string path = Path.Combine(Application.StartupPath, "Database1.mdf");

SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();

SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);

SqlDataReader reader = command.ExecuteReader();

while(reader.Read())
{
    string text = reader.GetString(0);
    MessageBox.Show(text);
}

SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("@i", 1);
c.Parameters.AddWithValue("@v", "Jack");

c.ExecuteNonQuery();

conn.Dispose();

This code is working for selection but not for insertion. 该代码适用于选择,但不适用于插入。 Then I hardcoded the path into: 然后我将路径硬编码为:

 String s = @"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";

and it works for both so it's not the SQL statement that is wrong. 它对两者都起作用,所以不是SQL语句出错。

So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work. 所以我的问题是:应该放入SqlConnection对象的路径是什么,以便当他们在竞争中获得我的源代码并在另一台PC上对其进行测试时它将起作用。

LocalDB is meant exclusively for development. LocalDB专用于开发。 You cannot use it in production. 您不能在生产中使用它。 In your case, 'production' means the competition. 在您的情况下,“生产”意味着竞争。 Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project. 除非竞赛组织者指定它们支持您连接的SQL Server实例并给出连接参数(即非常不可能),否则您不应在项目中使用use SQL Server。

You can put the MDF file on any file share that your computer has access to. 您可以将MDF文件放在计算机可以访问的任何文件共享上。 Just alter the path variable to point at the correct file share. 只需更改path变量以指向正确的文件共享即可。

See answers to your question here Can SQL Server Express LocalDB be connected to remotely? 在此处查看问题的答案是否可以将SQL Server Express LocalDB远程连接?

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

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