尝试保存到数据库时,代码似乎可以正常工作,但是表数据中什么也没有?

时间:2019-03-14 18:36:31

标签: database save connection database-connection connection-string

我正在尝试使用c#中的Visual Studio表单将数据保存到数据库中。在我所有的代码完成的那一刻,它正在“用户注册成功”,但是当我检查表数据时,那里什么也没有。

这是我DAL中的代码

 public static int AddNewCustomer(Models.Customer newCust)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                string sqlQuery = string.Format("INSERT INTO [Customer] VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}')", newCust.CustomerID, newCust.Title, newCust.Forename, newCust.Surname, newCust.Street, newCust.Town, newCust.PostCode, newCust.Email, newCust.TelNo, newCust.MobNo);

                SqlCommand insertCommand = new SqlCommand(sqlQuery, connection);

                int rowsAffected = insertCommand.ExecuteNonQuery();

                connection.Close();

                return rowsAffected;
            }
        }

然后这是我在表单中使用的代码:

 Models.Customer customer = new Models.Customer(int.Parse(lbl_CustID.Text), cbo_Title.Text, txt_CustomerForename.Text, txt_CustomerSurname.Text, txt_CustomerStreet.Text, txt_CustomerTown.Text, txt_CustomerPostCode.Text, txt_CustomerEmailAddress.Text, txt_CustomerTelephone.Text, txt_CustomerMobile.Text);
                                                int rowsAffected = WoodsideCommunityHub.DAL.CustomerDAL.AddNewCustomer(customer);

                                                if (rowsAffected == 1)
                                                {
                                                    MessageBox.Show("Customer successfully registered");
                                                    this.Hide();
                                                    Form myNextScreen = new frm_Child();
                                                    myNextScreen.ShowDialog();
                                                    this.Close();
                                                }
                                                else
                                                {
                                                    MessageBox.Show("Something went wrong there, please check that all feilds are entered correctly.");
                                                }

因此,似乎代码可以正常工作,但实际上并未保存到数据库中。 这是我的连接字符串:

<add name="Database1Connection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;" 
         providerName="System.Data.SqlClient"/>

感谢您的帮助,谢谢!

0 个答案:

没有答案