INSERT语句不添加任何数据而不会引发错误

时间:2018-11-25 08:39:26

标签: c# sql-server database

我正在尝试将训练对象添加到数据库中以保存其详细信息以保持持久性。

我正在使用它,因此可以将火车添加到列表中。但是,当我尝试建立一条INSERT语句以将训练对象的详细信息添加到数据库中时。当我检查之后,什么都没有添加到我的数据库中。我也不会在任何地方抛出任何错误。

有人可以看到我的INSERT语句有什么问题吗?

        //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();

2 个答案:

答案 0 :(得分:4)

整个 AttachDbFileName = 方法有缺陷-充其量!在Visual Studio中运行应用程序时,它将围绕.mdf文件(从App_Data目录复制到输出目录-通常为.\bin\debug-应用运行所在的目录)和很有可能,您的INSERT可以正常工作-但您最终只能看到错误的.mdf文件

如果您要坚持这种方法,请尝试在myConnection.Close()调用上放置一个断点-然后使用SQL Server Management Studio检查.mdf文件-我几乎可以确定您的数据是在那里。

我认为真正的解决方案

  1. 安装SQL Server Express(并且您已经完成了此操作)
  2. 安装SQL Server Management Studio
  3. 在SSMS中创建数据库,并为其指定一个逻辑名称(例如Trains
  4. 使用其逻辑数据库名称(在服务器上创建时提供)连接至它-请勿随意使用物理数据库文件和用户实例。在这种情况下,您的连接字符串将类似于:

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

    ,其他所有内容与以前完全一样 ...

有关更多背景信息,另请参见亚伦·伯特兰(Aaron Bertrand)的精彩博客文章Bad habits to kick: using AttachDbFileName

答案 1 :(得分:0)

尝试更改此代码

 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.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)";

我仅在您的INTO文本查询中添加了INSERT