0

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.

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Radu
  • 128
  • 1
  • 15
  • 1
    The target PC has to have the version of SQL server you're running and using as a connection string. Are you sure the target PC is running LocalDB? – Michael Puckett II Apr 08 '17 at 05:41

2 Answers2

0

LocalDB is meant exclusively for development. 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.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
0

You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.

See answers to your question here Can SQL Server Express LocalDB be connected to remotely?

Community
  • 1
  • 1
PhillipH
  • 6,182
  • 1
  • 15
  • 25