0

I need to input multiple rows at once with one insert statement from the data table into a database on PostgreSQL

insert into table1 values 
('1','aaa'),
('2','bbbb'),
('3','ccc')

this is my code to input multiple rows with one insert statement and its works

Sub bandingkan_data_tblpibconr()
        Dim Bs_access As New DataTable
        Bs_access = query.LoadAcces_tblpibconr
        Dim dt3 As New DataTable
        dt3 = Bs_access
        Cmd.Connection = connNpgsql.OpenConnection()


        Dim kueri As String

        kueri = "insert into tblpibconr values"
        For i = 0 To dt3.Rows.Count - 1



            kueri = kueri + "('" + dt3.Rows(i)("car").ToString + "','" + dt3.Rows(i)("reskd").ToString + "','" + dt3.Rows(i)("contno").ToString + "','" + dt3.Rows(i)("contukur").ToString.Trim() + "','" + dt3.Rows(i)("conttipe").ToString + "')"
            kueri = kueri + ","

        Next
        kueri = kueri.Remove(kueri.Length - 1, 1)

        Cmd.CommandText = kueri
        Cmd.ExecuteNonQuery()


        connNpgsql.CloseConexion()
    End Sub

but I need to add these parameters on my code

          Cmd.Parameters.AddWithValue("@car", NpgsqlTypes.NpgsqlDbType.Text).Value = dt3.Rows(i)("car").ToString
            Cmd.Parameters.AddWithValue("@reskd", NpgsqlTypes.NpgsqlDbType.Text).Value = dt3.Rows(i)("reskd").ToString
            Cmd.Parameters.AddWithValue("@contno", NpgsqlTypes.NpgsqlDbType.Text).Value = dt3.Rows(i)("contno").ToString
            Cmd.Parameters.AddWithValue("@contukur", NpgsqlTypes.NpgsqlDbType.Text).Value = dt3.Rows(i)("contukur").ToString.Trim()
            Cmd.Parameters.AddWithValue("@conttipe", NpgsqlTypes.NpgsqlDbType.Text).Value = dt3.Rows(i)("conttipe").ToString

I don't know how to combine my parameters and my kueri variable

kueri = kueri + "('" + dt3.Rows(i)("car").ToString + "','" + dt3.Rows(i)("reskd").ToString + "','" + dt3.Rows(i)("contno").ToString + "','" + dt3.Rows(i)("contukur").ToString.Trim() + "','" + dt3.Rows(i)("conttipe").ToString + "')"
            kueri = kueri + ","

can anyone help me?

And if you know how to input data from the data table into the PostgreSQL database faster then this method using vb.net please let me know.

2
  • Why are you creating three DataTables and only using one of them? The New keyword is used to create a new object so don't use it unless you actually want a new object. The first four lines of that method should be replaced with one: Dim table As DataTable = query.LoadAcces_tblpibconr(). Commented Sep 23, 2020 at 4:21
  • You conclude the wrong outcome in your requirement: It is possible to add multiple values w/ one roundtrip to the database without having the comma-separated syntax you provided. Just use the DataAdapter like @jmcilhinney demonstrated in his answer. If you don´t understand it, google it, there are a lot of tutorials about it and come back if you have a specific problem Commented Sep 23, 2020 at 5:51

2 Answers 2

1

You don't loop through a DataTable to save data. You use a data adapter to save the lot in one go. I'll provide an example to demonstrate the principle and let you apply that principle to your specific scenario.

'Create and populate the DataTable.
Dim table As New DataTable

With table.Columns
    .Add("Name", GetType(String))
    .Add("Amount", GetType(Integer))
End With

With table.Rows
    .Add("One", 1)
    .Add("Two", 2)
    .Add("Three", 3)
End With

'Create the data adapter.
Using connection As New SqlConnection("connection string here"),
      command As New SqlCommand("INSERT INTO MyTable (Name, Amount) VALUES (@Name, @Amount)", connection),
      adapter As New SqlDataAdapter With {.InsertCommand = command}
    'Add parameters.
    With command.Parameters
        .Add("@Name", SqlDbType.VarChar, 50, "Name")
        .Add("@Amount", SqlDbType.Int, 0, "Amount")
    End With

    'Save data.
    adapter.Update(table)
End Using

You need to make sure that the RowState of each DataRow is Added in order for them to be inserted. If you have added the rows in code, as I have above, then they already will be. If you're populating the DataTable with a data adapter then you can set its AcceptChangesOnFill property to False to leave the rows in that state. Otherwise, you can call SetAdded on each row.

You might check here for more information.

Sign up to request clarification or add additional context in comments.

2 Comments

hey sir can u explain more for me? because I don't think your code has the same method as mine what I need is to import multiple values with 1 execute sir. I'm sorry if I'm wrong because I am new to this sir thanks...
A single INSERT command can only insert a single record. the way to insert multiple records is how I have deomstrated here. If you don't understand it then you don't understand the basics of ADO.NET, so you need to spend some time fixing that. This site is not for teaching you the basics. It is for help with specific issues, which I have provided. We should be able to assume that you either understand the fundamentals required to make use of the solution provided or will spend the time learning those fundamentals for yourself.
0

The Using...End Using block assures that your connection and command are closed and disposed even if there is an error. If possible always list your field names in your sql statement. I had to guess at the names.

Add the parameters once outside the loop. Then just reset the values of the parameters on each iteration.

Sub bandingkan_data_tblpibconr()
    Dim dt3 = query.LoadAcces_tblpibconr
    Using cn As New NpgsqlConnection(ConStr),
            cmd As New NpgsqlCommand("insert into tblpibconr (Car, Reskd, Contno, Contukur, Conttipe) Values (@car, @reskd, @contno, @contukur, @conttipe);")
        With cmd.Parameters
            .Add("@car", NpgsqlTypes.NpgsqlDbType.Text)
            .Add("@reskd", NpgsqlTypes.NpgsqlDbType.Text)
            .Add("@contno", NpgsqlTypes.NpgsqlDbType.Text)
            .Add("@contukur", NpgsqlTypes.NpgsqlDbType.Text)
            .Add("@conttipe", NpgsqlTypes.NpgsqlDbType.Text)
        End With
        cn.Open()
        For Each row As DataRow In dt3.Rows
            cmd.Parameters("@car").Value = row("car").ToString
            cmd.Parameters("@reskd").Value = row("reskd").ToString
            cmd.Parameters("@contno").Value = row("contno").ToString
            cmd.Parameters("@contukur").Value = row("contukur").ToString
            cmd.Parameters("@conttipe").Value = row("conttipe").ToString
            cmd.ExecuteNonQuery()
        Next
    End Using
End Sub

9 Comments

sir, I have tried ur code and it still needs looping the execute .is it possible to put the cmd.ExecuteNonQuery() outside the loop ? like my code above but with parameters
Mary I guess you habe a copy/paste error in your loop regarding parameter name @car
Additionally, that isn´t really what @Felix wanted. This solution fires one roundtrip to DB foreach row.
@AlexB. Thanks for noticing the paste error. There is a single connection - single trip to DB, the query is cached and the plan reused.
@Mary I know the meaning of query plans, I referred to the part that every round trip from a client to the database consumes time and ressources (like Network I/O). So like you said Into...Select or passing a table valued parameter should always be preferred when dealing with mass data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.