INSERT statement not adding any data without throwing error





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I am trying to add train objects to a database to hold their details for persistence.



I have it working so I can add the trains to a list. But when I try to set up an INSERT statement to add the train objects details to a database. nothing is added to my database when i check it after. I don't get any errors thrown anywhere either.



Can anyone see anything wrong with my INSERT statement?



        //If the type combobox has Express selected
if (cbxType.Text == "Express")
{
//Create a new train with its specific details
Train train = trainFactory.TFactory("Express");
//Checks for error when making train
if (train == null)
MessageBox.Show("Can't Create Train");
else //Executes adding a new Express Train
{
//Stores the details of the textboxes/Combo boxes into the train details for each Train object
train.Type = cbxType.Text;
train.Departure = cbxDepartStation.Text;
train.Destination = cbxDepartStation.Text;
//Converts the time into DateTime format before passing to variable
train.DepartureTime = TimeSpan.Parse(txtDepartureTime.Text);
//Converts the date into DateTime format before passing to variable
train.DepartureDay = DateTime.Parse(txtDepartureDay.Text);
//If intermediate stops are selected. Throw exception
if (chbPeterborough.IsChecked == true || chbDarlington.IsChecked == true ||
chbYork.IsChecked == true || chbNewcastle.IsChecked == true)
{
throw new Exception();
}
//If first class radio button is checked, sets first class to true, else false
if (chbFirstClass.IsChecked == true)
{
train.FirstClass = true;
}
else
{
train.FirstClass = false;
}

//Adds a train object to the train list with its specific details
trains.add(train);

//String to hold all the Intermediate stops together in one for displaying to user
string intStops = string.Join(", ", train.IntermediateStop.Where(s => !string.IsNullOrEmpty(s)));

//Sql sequence to connect to database and insert details of each train
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|Trains.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";
cmd.Parameters.AddWithValue("@trainID", train.TrainID);
cmd.Parameters.AddWithValue("@departure", train.Departure);
cmd.Parameters.AddWithValue("@destination", train.Destination);
cmd.Parameters.AddWithValue("@type", train.Type);
cmd.Parameters.AddWithValue("@intermediate", intStops);
cmd.Parameters.AddWithValue("@dep_time", train.DepartureTime);
cmd.Parameters.AddWithValue("@dep_date", train.DepartureDay);
cmd.Parameters.AddWithValue("@sleep", train.SleeperBerth);
cmd.Parameters.AddWithValue("@first", train.FirstClass);

cmd.Connection = con;

con.Open();
cmd.ExecuteNonQuery();
con.Close();









share|improve this question




















  • 3





    It seems that you are in this situation stackoverflow.com/questions/17147249/…

    – Steve
    Nov 25 '18 at 8:44


















1















I am trying to add train objects to a database to hold their details for persistence.



I have it working so I can add the trains to a list. But when I try to set up an INSERT statement to add the train objects details to a database. nothing is added to my database when i check it after. I don't get any errors thrown anywhere either.



Can anyone see anything wrong with my INSERT statement?



        //If the type combobox has Express selected
if (cbxType.Text == "Express")
{
//Create a new train with its specific details
Train train = trainFactory.TFactory("Express");
//Checks for error when making train
if (train == null)
MessageBox.Show("Can't Create Train");
else //Executes adding a new Express Train
{
//Stores the details of the textboxes/Combo boxes into the train details for each Train object
train.Type = cbxType.Text;
train.Departure = cbxDepartStation.Text;
train.Destination = cbxDepartStation.Text;
//Converts the time into DateTime format before passing to variable
train.DepartureTime = TimeSpan.Parse(txtDepartureTime.Text);
//Converts the date into DateTime format before passing to variable
train.DepartureDay = DateTime.Parse(txtDepartureDay.Text);
//If intermediate stops are selected. Throw exception
if (chbPeterborough.IsChecked == true || chbDarlington.IsChecked == true ||
chbYork.IsChecked == true || chbNewcastle.IsChecked == true)
{
throw new Exception();
}
//If first class radio button is checked, sets first class to true, else false
if (chbFirstClass.IsChecked == true)
{
train.FirstClass = true;
}
else
{
train.FirstClass = false;
}

//Adds a train object to the train list with its specific details
trains.add(train);

//String to hold all the Intermediate stops together in one for displaying to user
string intStops = string.Join(", ", train.IntermediateStop.Where(s => !string.IsNullOrEmpty(s)));

//Sql sequence to connect to database and insert details of each train
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|Trains.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";
cmd.Parameters.AddWithValue("@trainID", train.TrainID);
cmd.Parameters.AddWithValue("@departure", train.Departure);
cmd.Parameters.AddWithValue("@destination", train.Destination);
cmd.Parameters.AddWithValue("@type", train.Type);
cmd.Parameters.AddWithValue("@intermediate", intStops);
cmd.Parameters.AddWithValue("@dep_time", train.DepartureTime);
cmd.Parameters.AddWithValue("@dep_date", train.DepartureDay);
cmd.Parameters.AddWithValue("@sleep", train.SleeperBerth);
cmd.Parameters.AddWithValue("@first", train.FirstClass);

cmd.Connection = con;

con.Open();
cmd.ExecuteNonQuery();
con.Close();









share|improve this question




















  • 3





    It seems that you are in this situation stackoverflow.com/questions/17147249/…

    – Steve
    Nov 25 '18 at 8:44














1












1








1








I am trying to add train objects to a database to hold their details for persistence.



I have it working so I can add the trains to a list. But when I try to set up an INSERT statement to add the train objects details to a database. nothing is added to my database when i check it after. I don't get any errors thrown anywhere either.



Can anyone see anything wrong with my INSERT statement?



        //If the type combobox has Express selected
if (cbxType.Text == "Express")
{
//Create a new train with its specific details
Train train = trainFactory.TFactory("Express");
//Checks for error when making train
if (train == null)
MessageBox.Show("Can't Create Train");
else //Executes adding a new Express Train
{
//Stores the details of the textboxes/Combo boxes into the train details for each Train object
train.Type = cbxType.Text;
train.Departure = cbxDepartStation.Text;
train.Destination = cbxDepartStation.Text;
//Converts the time into DateTime format before passing to variable
train.DepartureTime = TimeSpan.Parse(txtDepartureTime.Text);
//Converts the date into DateTime format before passing to variable
train.DepartureDay = DateTime.Parse(txtDepartureDay.Text);
//If intermediate stops are selected. Throw exception
if (chbPeterborough.IsChecked == true || chbDarlington.IsChecked == true ||
chbYork.IsChecked == true || chbNewcastle.IsChecked == true)
{
throw new Exception();
}
//If first class radio button is checked, sets first class to true, else false
if (chbFirstClass.IsChecked == true)
{
train.FirstClass = true;
}
else
{
train.FirstClass = false;
}

//Adds a train object to the train list with its specific details
trains.add(train);

//String to hold all the Intermediate stops together in one for displaying to user
string intStops = string.Join(", ", train.IntermediateStop.Where(s => !string.IsNullOrEmpty(s)));

//Sql sequence to connect to database and insert details of each train
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|Trains.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";
cmd.Parameters.AddWithValue("@trainID", train.TrainID);
cmd.Parameters.AddWithValue("@departure", train.Departure);
cmd.Parameters.AddWithValue("@destination", train.Destination);
cmd.Parameters.AddWithValue("@type", train.Type);
cmd.Parameters.AddWithValue("@intermediate", intStops);
cmd.Parameters.AddWithValue("@dep_time", train.DepartureTime);
cmd.Parameters.AddWithValue("@dep_date", train.DepartureDay);
cmd.Parameters.AddWithValue("@sleep", train.SleeperBerth);
cmd.Parameters.AddWithValue("@first", train.FirstClass);

cmd.Connection = con;

con.Open();
cmd.ExecuteNonQuery();
con.Close();









share|improve this question
















I am trying to add train objects to a database to hold their details for persistence.



I have it working so I can add the trains to a list. But when I try to set up an INSERT statement to add the train objects details to a database. nothing is added to my database when i check it after. I don't get any errors thrown anywhere either.



Can anyone see anything wrong with my INSERT statement?



        //If the type combobox has Express selected
if (cbxType.Text == "Express")
{
//Create a new train with its specific details
Train train = trainFactory.TFactory("Express");
//Checks for error when making train
if (train == null)
MessageBox.Show("Can't Create Train");
else //Executes adding a new Express Train
{
//Stores the details of the textboxes/Combo boxes into the train details for each Train object
train.Type = cbxType.Text;
train.Departure = cbxDepartStation.Text;
train.Destination = cbxDepartStation.Text;
//Converts the time into DateTime format before passing to variable
train.DepartureTime = TimeSpan.Parse(txtDepartureTime.Text);
//Converts the date into DateTime format before passing to variable
train.DepartureDay = DateTime.Parse(txtDepartureDay.Text);
//If intermediate stops are selected. Throw exception
if (chbPeterborough.IsChecked == true || chbDarlington.IsChecked == true ||
chbYork.IsChecked == true || chbNewcastle.IsChecked == true)
{
throw new Exception();
}
//If first class radio button is checked, sets first class to true, else false
if (chbFirstClass.IsChecked == true)
{
train.FirstClass = true;
}
else
{
train.FirstClass = false;
}

//Adds a train object to the train list with its specific details
trains.add(train);

//String to hold all the Intermediate stops together in one for displaying to user
string intStops = string.Join(", ", train.IntermediateStop.Where(s => !string.IsNullOrEmpty(s)));

//Sql sequence to connect to database and insert details of each train
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|Trains.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";
cmd.Parameters.AddWithValue("@trainID", train.TrainID);
cmd.Parameters.AddWithValue("@departure", train.Departure);
cmd.Parameters.AddWithValue("@destination", train.Destination);
cmd.Parameters.AddWithValue("@type", train.Type);
cmd.Parameters.AddWithValue("@intermediate", intStops);
cmd.Parameters.AddWithValue("@dep_time", train.DepartureTime);
cmd.Parameters.AddWithValue("@dep_date", train.DepartureDay);
cmd.Parameters.AddWithValue("@sleep", train.SleeperBerth);
cmd.Parameters.AddWithValue("@first", train.FirstClass);

cmd.Connection = con;

con.Open();
cmd.ExecuteNonQuery();
con.Close();






c# sql-server database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 8:52









John

14.4k42645




14.4k42645










asked Nov 25 '18 at 8:39









ESuthESuth

707




707








  • 3





    It seems that you are in this situation stackoverflow.com/questions/17147249/…

    – Steve
    Nov 25 '18 at 8:44














  • 3





    It seems that you are in this situation stackoverflow.com/questions/17147249/…

    – Steve
    Nov 25 '18 at 8:44








3




3





It seems that you are in this situation stackoverflow.com/questions/17147249/…

– Steve
Nov 25 '18 at 8:44





It seems that you are in this situation stackoverflow.com/questions/17147249/…

– Steve
Nov 25 '18 at 8:44












2 Answers
2






active

oldest

votes


















4














The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .bindebug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!



If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Management Studio - I'm almost certain your data is there.



The real solution in my opinion would be to




  1. install SQL Server Express (and you've already done that anyway)

  2. install SQL Server Management Studio

  3. create your database in SSMS, give it a logical name (e.g. Trains)


  4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:



    Data Source=.\SQLEXPRESS;Database=Trains;Integrated Security=True


    and everything else is exactly the same as before...




Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.






share|improve this answer
























  • He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

    – Steve
    Nov 25 '18 at 8:53











  • @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

    – marc_s
    Nov 25 '18 at 8:55











  • Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

    – Steve
    Nov 25 '18 at 9:00






  • 1





    @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

    – marc_s
    Nov 25 '18 at 10:13








  • 1





    Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

    – ESuth
    Nov 25 '18 at 11:00



















0














Try to change this code



 cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


into



 cmd.CommandText = "INSERT INTO train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
"VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


I only added INTO in your INSERT text query






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465896%2finsert-statement-not-adding-any-data-without-throwing-error%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .bindebug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!



    If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Management Studio - I'm almost certain your data is there.



    The real solution in my opinion would be to




    1. install SQL Server Express (and you've already done that anyway)

    2. install SQL Server Management Studio

    3. create your database in SSMS, give it a logical name (e.g. Trains)


    4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:



      Data Source=.\SQLEXPRESS;Database=Trains;Integrated Security=True


      and everything else is exactly the same as before...




    Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.






    share|improve this answer
























    • He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

      – Steve
      Nov 25 '18 at 8:53











    • @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

      – marc_s
      Nov 25 '18 at 8:55











    • Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

      – Steve
      Nov 25 '18 at 9:00






    • 1





      @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

      – marc_s
      Nov 25 '18 at 10:13








    • 1





      Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

      – ESuth
      Nov 25 '18 at 11:00
















    4














    The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .bindebug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!



    If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Management Studio - I'm almost certain your data is there.



    The real solution in my opinion would be to




    1. install SQL Server Express (and you've already done that anyway)

    2. install SQL Server Management Studio

    3. create your database in SSMS, give it a logical name (e.g. Trains)


    4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:



      Data Source=.\SQLEXPRESS;Database=Trains;Integrated Security=True


      and everything else is exactly the same as before...




    Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.






    share|improve this answer
























    • He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

      – Steve
      Nov 25 '18 at 8:53











    • @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

      – marc_s
      Nov 25 '18 at 8:55











    • Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

      – Steve
      Nov 25 '18 at 9:00






    • 1





      @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

      – marc_s
      Nov 25 '18 at 10:13








    • 1





      Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

      – ESuth
      Nov 25 '18 at 11:00














    4












    4








    4







    The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .bindebug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!



    If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Management Studio - I'm almost certain your data is there.



    The real solution in my opinion would be to




    1. install SQL Server Express (and you've already done that anyway)

    2. install SQL Server Management Studio

    3. create your database in SSMS, give it a logical name (e.g. Trains)


    4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:



      Data Source=.\SQLEXPRESS;Database=Trains;Integrated Security=True


      and everything else is exactly the same as before...




    Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.






    share|improve this answer













    The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .bindebug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!



    If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Management Studio - I'm almost certain your data is there.



    The real solution in my opinion would be to




    1. install SQL Server Express (and you've already done that anyway)

    2. install SQL Server Management Studio

    3. create your database in SSMS, give it a logical name (e.g. Trains)


    4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:



      Data Source=.\SQLEXPRESS;Database=Trains;Integrated Security=True


      and everything else is exactly the same as before...




    Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 25 '18 at 8:48









    marc_smarc_s

    587k13011281274




    587k13011281274













    • He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

      – Steve
      Nov 25 '18 at 8:53











    • @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

      – marc_s
      Nov 25 '18 at 8:55











    • Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

      – Steve
      Nov 25 '18 at 9:00






    • 1





      @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

      – marc_s
      Nov 25 '18 at 10:13








    • 1





      Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

      – ESuth
      Nov 25 '18 at 11:00



















    • He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

      – Steve
      Nov 25 '18 at 8:53











    • @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

      – marc_s
      Nov 25 '18 at 8:55











    • Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

      – Steve
      Nov 25 '18 at 9:00






    • 1





      @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

      – marc_s
      Nov 25 '18 at 10:13








    • 1





      Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

      – ESuth
      Nov 25 '18 at 11:00

















    He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

    – Steve
    Nov 25 '18 at 8:53





    He is using LocalDB probably because he doesn't want to use the full installation of SqlServer Express and he wants to distribute its app to his customers without worrying about distributing also Sql Server and forcing them to go through the whole process of installing Sql Server Express

    – Steve
    Nov 25 '18 at 8:53













    @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

    – marc_s
    Nov 25 '18 at 8:55





    @Steve: if anyone is serious about developing with SQL Server, installing SQL Server Express is a very small step and well worth it, to avoid troubles like this all the time. And also: if he wants to distribute this, he must deal with installing SQL Server anyway - one way or another....

    – marc_s
    Nov 25 '18 at 8:55













    Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

    – Steve
    Nov 25 '18 at 9:00





    Well, in my experience this is not always true. Suppose you have a demo of your full app downloadable from Internet. Your anonymous customers want to test your app before buying it. You don't want to spend time installing and configuring Sql Server for them. But of course, if they like your app and decide to buy it then your are more than happy to install Sql Server Express for them. I agree with you on the flawed AttachDbFileName approach

    – Steve
    Nov 25 '18 at 9:00




    1




    1





    @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

    – marc_s
    Nov 25 '18 at 10:13







    @ESuth: if you've installed SQL Server Express with all the default settings, this creates a named instance of SQL Server - connect to it using .SQLEXPRESS (or (local)SQLEXPRESS) as server/instance name - as shown and mentioned in my answer, too .....

    – marc_s
    Nov 25 '18 at 10:13






    1




    1





    Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

    – ESuth
    Nov 25 '18 at 11:00





    Nevermind. Got it all working now and I can see the results now when checking the database. Thank you so much.

    – ESuth
    Nov 25 '18 at 11:00













    0














    Try to change this code



     cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
    "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


    into



     cmd.CommandText = "INSERT INTO train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
    "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


    I only added INTO in your INSERT text query






    share|improve this answer




























      0














      Try to change this code



       cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
      "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


      into



       cmd.CommandText = "INSERT INTO train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
      "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


      I only added INTO in your INSERT text query






      share|improve this answer


























        0












        0








        0







        Try to change this code



         cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
        "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


        into



         cmd.CommandText = "INSERT INTO train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
        "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


        I only added INTO in your INSERT text query






        share|improve this answer













        Try to change this code



         cmd.CommandText = "INSERT train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
        "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


        into



         cmd.CommandText = "INSERT INTO train (id, departure, destination, type, intermediate, departure_time, departure_date, sleeperBerth, firstClass) " +
        "VALUES ( @trainID , @departure, @destination, @type, @intermediate, @dep_time, @dep_date, @sleep, @first)";


        I only added INTO in your INSERT text query







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 1:28









        klitzklitz

        285




        285






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465896%2finsert-statement-not-adding-any-data-without-throwing-error%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings