Insert data from Visual Studio to SQL Server

0

How can I solve this problem when inserting data from Visual Studio.net into SQL? This is my code that I use:

Imports System.Data.SqlClient

Public Class Form1

Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles BtnInsertar.Click
    Dim conexion As SqlConnection
    conexion = New SqlConnection("server=USER-PC; database=base1; integrated security=true")
    conexion.Open()

    Dim placa As String = TxtPlaca.Text
    Dim marca As String = TxtMarca.Text
    Dim cilindraje As String = TxtCilindraje.Text
    Dim color As String = TxtColor.Text
    Dim modelo As String = TxtModelo.Text

    Dim cadena As String = "insert into automovil (placa, marca, cilindraje, color, modelo) values (" & placa & ",'" & marca & "', " & cilindraje & ",'" & color & "','" & modelo & "')"

    Dim comando As SqlCommand
    comando = New SqlCommand(cadena, conexion)
    comando.ExecuteNonQuery()

    MessageBox.Show("Datos Ingresados Correctamente")

    TxtPlaca.Text = ""
    TxtMarca.Text = ""
    TxtCilindraje.Text = ""
    TxtColor.Text = ""
    TxtModelo.Text = ""

    conexion.Close()
End Sub
End Class

But I detected an error in this line:

comando.ExecuteNonQuery()

How can I solve it, I'm a beginner

    
asked by Josue Cabrera 24.07.2017 в 00:43
source

1 answer

0

The error is quite clear, you are trying to insert an explicit value in the automovil table in a column that does not allow it, possibly placa , because it is of the type IDENTITY , which in basic Spanish means that it is a self-numerical column, that is, it corresponds to the engine updating it, you can not explicitly configure a value. What you must do is remove it from the INSERT statement and let the data base take care of establishing the value. If you will eventually need to recover the value of this column once inserted you can use the % function SCOPE_IDENTITY() .

Obviously if placa is the IDENTITY as I imagine, in your example you should do this:

Dim cadena As String = "insert into automovil (marca, cilindraje, color, modelo) values ('" & marca & "', " & cilindraje & ",'" & color & "','" & modelo & "')"

Clarification : when I say that you can not set the value of this column, I should say that it is not advisable to do it in most cases, under certain circumstances you can do a SET IDENTITY_INSERT automoviles ON; , insert the specific value to the column and return everything to normal with SET IDENTITY_INSERT automoviles OFF; , but in your example, it does not make any sense to do so.

    
answered by 24.07.2017 / 01:34
source