尝试将数据插入数据库时​​抛出异常错误

时间:2017-03-02 11:34:17

标签: c# sql-server

我收到一个错误,抛出一个像标题一样的异常。我不确定是什么问题

连接:

    public void connectToDatabase()
    {
        connStrBuilder = new SqlConnectionStringBuilder();
        connStrBuilder.DataSource = @"DESK-KEGRC\SQLSERVER";
        connStrBuilder.InitialCatalog = "RentalDatabase";
        connStrBuilder.IntegratedSecurity = true;

        connection = new SqlConnection(connStrBuilder.ToString());

    }

    public void Insert(Car car)
    {
        try
        {
            string commandText = "INSERT INTO dbo.Cars(Brand, Name, Year) VALUES (@Brand, @Name, @Year)";
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.AddWithValue("@Brand", car.newBrand);
            command.Parameters.AddWithValue("@Name", car.newName);
            command.Parameters.AddWithValue("@Year", car.newRegisteredYear);
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch
        {
            throw;
        }
    }

这是将数据插入数据库的事件按钮

 private void InsertData(object sender, EventArgs e)
    {
        car = new Car();
        car.newBrand = txtBrand.Text;
        car.newName = txtName.Text;
        car.newRegisteredYear = txtYear.Text;
        dataBaseConnection.Insert(car);
    }

错误:

  

System.NullReferenceException:未将对象引用设置为对象的实例。      at ConnectToDatabase.DatabaseConnection.Insert(Car car)在C:\ Users \ Kopalnia \ Desktop \ C#\ Program \ VehicleRental \ VehicleRental \ Vehicle Rental \ ConnectToDatabase \ DatabaseConnection.cs:第46行      at Vehicl_Rental.AddACar.InsertData(Object sender,EventArgs e)位于C:\ Users \ Kopalnia \ Desktop \ C#\ Program \ VehicleRental \ VehicleRental \ Vehicle Rental \ Vehicl Rental \ AddACar.cs:第31行

1 个答案:

答案 0 :(得分:3)

您必须先致电connectToDatabase()

private void InsertData(object sender, EventArgs e)
{
        connectToDatabase()
        car = new Car();
        car.newBrand = txtBrand.Text;
        car.newName = txtName.Text;
        car.newRegisteredYear = txtYear.Text;
        dataBaseConnection.Insert(car);
}