VB.NET Inserting data into database from data view grid - sql-server

I would like to ask is there anyway I can improve my speed when inserting all my data that is from the data grid.
For example:
I have 10,000 data currently needed to insert to the database sql server.
Now, I would like to insert all the data into the database.
But I feel that it would be slow.
Can I do it without using for loop?
Dim chk_cmd As SqlCommand
Dim chk_con As SqlConnection
Dim checker As SqlDataReader
Dim chkint As Integer = 0
Dim constring As String = "Data Source=exmag\sqlexpress;Initial Catalog=Stock;Integrated Security=true;"
Try
For Each row As DataGridViewRow In DataGridView1.Rows
chk_con = New SqlConnection(constring)
chk_con.Open()
chk_cmd = New SqlCommand("SELECT stockId FROM stock WHERE stockId = '" & row.Cells("stockId").Value & "'", chk_con)
checker = chk_cmd.ExecuteReader(CommandBehavior.CloseConnection)
If checker.HasRows Then
chkint += 1
Else
Using con_insert As New SqlConnection(constring), cmd_insert As New SqlCommand("INSERT INTO stock VALUES(#stockId,#id_android,#itemCode,#quantity)", con_insert)
cmd_insert.Parameters.AddWithValue("#stockId", row.Cells("stockId").Value)
cmd_insert.Parameters.AddWithValue("#id_android", row.Cells("id_android").Value)
cmd_insert.Parameters.AddWithValue("#itemCode", row.Cells("itemCode").Value)
cmd_insert.Parameters.AddWithValue("#quantity", row.Cells("quantity").Value)
con_insert.Open()
cmd_insert.ExecuteNonQuery()
con_insert.Close()
End Using
End If
Next
Catch ex As SqlException
If ex.Number.Equals(2627) Then
MsgBox("Primary Key DUPLICATED/Some Data are currently in the table.")
End If
End Try
MsgBox(chkint & " Data has duplicated primary key!")

You can update a database using a DataTable and DataAdapter
A brief online below.
// con = SqlConnection '
// queryString = your SELECT query
Using da As New SqlDataAdapter()
da.SelectCommand = New SqlCommand( _
queryString, connection)
Dim dt As New DataTable("TABLE_NAME")
da.Fill(dt)
// Loop through your collection
// Add new Row to datatable
// Populate new row
Dim drow As DataRow = dt.NewRow()
drow("Example Field") = "Example String"
// Update database
dt.Add(drow)
da.update(dt)
End Using
N.B. Used double-slash instead of an apostrophe for comments as SO seems to be highlighting syntax incorrectly with apostrophes.

Here's one way of doing this; I use it to transfer spreadsheets.
I agree with jmcilhinney that getting 10000 records in a grid is pointless.
// create a datatable
Dim dt_eff As New DataTable
dt_eff.Columns.Add("Element", GetType(String))
dt_eff.Columns.Add("Eff", GetType(Decimal))
dt_eff.PrimaryKey = New DataColumn() {dt_eff.Columns("Element")}
// fill the datatable
For row As Integer = 4 To 50
newRow = dt_eff.NewRow
newRow("Element") = wsComp.Cells(row, 1).Value.ToString
newRow("Eff") = CDec(wsComp.Cells(row, 6).Value)
dt_eff.Rows.Add(newRow)
Next
// send the datatable to a sp on SQL SERVER
Dim param As SqlClient.SqlParameter
Using selectcmd As New SqlClient.SqlCommand("[dbo].[LoadingTable_IntegrateIncoming]", trans.Connection, trans)
selectcmd.CommandType = CommandType.StoredProcedure
param = selectcmd.Parameters.AddWithValue("#Efficiencies", dt_eff)
param.SqlDbType = SqlDbType.Structured
selectcmd.ExecuteNonQuery()
End Using
// on the server side: declare a table type
CREATE TYPE [dbo].[TVP_Efficiencies] AS TABLE(
[Element] [nvarchar](5) NOT NULL,
[Eff] [decimal](18, 4) NOT NULL,
PRIMARY KEY CLUSTERED
(
[Element] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
// and create a stored proc that consumes the datatable
CREATE PROCEDURE [dbo].[LoadingTable_IntegrateIncoming]
#Efficiencies TVP_Efficiencies readonly
AS
BEGIN
SET NOCOUNT ON;
insert into efficiencies
select * from #Efficiencies
END

Related

Add ORDER BY clause in VB.Net?

How to concatenate
ORDER BY
clause in VB.NET?
Here's what I've tried:
Using command As New SqlCommand()
command.Connection = conn
Dim parameterNames As New List(Of String)(dt_data.RowCount - 2)
For i As Integer = 0 To dt_data.RowCount - 3
Dim parameterName As String = "#meter_num_" & i
Dim meter_number As String = dt_data.Rows(i).Cells(3).Value
command.Parameters.AddWithValue(parameterName, meter_number)
parameterNames.Add(parameterName)
Next
command.CommandText = String.Format("SELECT * FROM customer WHERE cycle = #cycle and meter_num IN ({0})", String.Join(",", parameterNames), ("ORDER BY Client_Name ASC"))
command.Parameters.AddWithValue("#cycle", cycle2last)
Dim da As New SqlDataAdapter(command)
Dim ds As New DataSet
da.Fill(ds, "customer")
Compare_Reading.dt_last2month.DataSource = ds.Tables(0)
End Using
I wanted it to be like this
Select * from table_name
where column_name = #column and column2 = #column2
ORDER BY column_name ASC
To do that in a single instruction you need to replace
Compare_Reading.dt_last2month.DataSource = ds.Tables(0)
With:
Compare_Reading.dt_last2month.DataSource = (From existing As DataRow In ds.Tables(0).Select Order By existing.Item("your_filed_name_to_order_here") Ascending).CopyToDataTable
One of the nice things about List(Of T) is that you don't need to know the size before adding items. It will expand as necessary. So, I deleted the int32 from the constructor.
I think you want dt_data.RowCount -2 in For loop or you will skip the last row. I changed your .AddWithValue to .Add. You will have to check your database for the correct datatypes (I guessed) and adjust the code accordingly.
I think your main problem was in String.Format. You added the 2 parameters but neglected to put in the {1}.
I added a Debug.Print so you can check that your Select looks like you expect. This will appear in the immediate window when you run in debug. It won't effect the release version.
You don't need a DataAdapter or DataSet just a DataTable. Assign the .DataSource outside of the Using block.
I don't think there is any concern about sql injection because you have properly used parameters for all the variables.
Private Sub OPCode(cycle2last As String)
Dim dt As New DataTable
Using conn As New SqlConnection("Your connection string")
Using command As New SqlCommand()
command.Connection = conn
Dim parameterNames As New List(Of String)
For i As Integer = 0 To DataGridView1.RowCount - 2
Dim parameterName As String = "#meter_num_" & i
Dim meter_number As String = DataGridView1.Rows(i).Cells(3).Value.ToString
command.Parameters.Add(parameterName, SqlDbType.VarChar).Value = meter_number
parameterNames.Add(parameterName)
Next
command.CommandText = String.Format("SELECT * FROM customer WHERE cycle = #cycle and meter_num IN ({0}) {1}", String.Join(",", parameterNames), ("ORDER BY Client_Name ASC;"))
command.Parameters.Add("#cycle", SqlDbType.VarChar).Value = cycle2last
Debug.Print(command.CommandText)
conn.Open()
dt.Load(command.ExecuteReader)
End Using
End Using
DataGridView2.DataSource = dt
End Sub

Running SQL Server query in VB.NET

How would I create a query that returns a column in the database? The SQL select statement is easy. I'm having issues with the VB side.
SELECT UserNO
FROM UserTable
WHERE UserID = user;
I need to then get that UserNO and pass it to another T-SQL stored procedure. How would I go about running a SELECT query and getting the results back in Visual Basic?
Attached is some of my code. The code below adds the user to the DB however the UserNo (INTEGER) is automatically generated by SQL Server as the INSERT statement is run in the insert stored procedure, so I need to pull the UserNO after the user is created.
Public conwd As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Public conwp As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwp)
Dim cmdD As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwd)
conmp.Open()
conmd.Open()
cmdP.ExecuteNonQuery()
cmdD.ExecuteNonQuery()
The Using..End Using blocks close and dispose of your data objects that might contain unmanaged code. The Parameters help prevent SQL injection.
Private Sub OPCode2()
Dim newID As Integer
Dim sql = "Insert Into UserTable (User) Values (#User); Select SCOPE_IDENTITY();"
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#User", SqlDbType.NVarChar).Value = "Brian Weaver"
cn.Open()
newID = CInt(cmd.ExecuteScalar)
End Using
End Using
'Use the newID in your next command
UserStoredProcedure(newID)
End Sub
Private Sub UseStoredProcedure(id As Integer)
Dim sql = "InsertSomeUserInfo" 'the name of your stored procedure
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.CommandType = CommandType.StoredProcedure
'whatever parameter names and types your stored procedure uses
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = id
cmd.Parameters.Add("#Salary", SqlDbType.Decimal).Value = 50000
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'" + "; SELECT CAST(scope_identity() AS int", conwp)
Dim userNo as Integer = cmdP.ExecuteScalar()
ExecuteScalar retrieves the first line of the result

how to get each unique value from access database column and add to combobox items

I am not professional but i am trying to learn VB.net. I am making a project where i am stuck where i want to get each unique value from a column in access database and add it to my combobox. Can anybody help me ??
Private Sub showItems()
Dim comm As OleDbCommand
Dim commStr As String = "SELECT Item_Name FROM Add_Items WHERE (Item_Name <> '"
Dim RD As OleDbDataReader
conn = New OleDbConnection(connStr)
conn.Open()
If cbItemname.Items.Count = 0 Then
comm = New OleDbCommand("Select Item_Name from Add_Items", conn)
RD = comm.ExecuteReader
While RD.Read
cbItemname.Items.Add(RD.GetString(0))
End While
End If
For Each i As Object In cbItemname.Items
comm = New OleDbCommand(commStr & i & "')", conn)
RD = comm.ExecuteReader
While RD.Read
cbItemname.Items.Add(RD.GetString(0))
Exit While
End While
Next
conn.Close()
End Sub
comm = New OleDbCommand("Select DISTINCT Item_Name from Add_Items", conn)
http://office.microsoft.com/en-in/access-help/HV080760568.aspx
You can get this error because your database table name is incorrect. Make sure you are in the Tables tab and check the name of the table. DISTINCT and UNIQUE(for MySQL) is correct solution for this.
I followed instructions given by vipul. It was working nicely and i made some more private subs for brands and Models and it suddenly stopped working. Now, when my form loads from previous parent form it hangs.
Private Sub showItems()
Dim comm As OleDbCommand
Dim commStr As String = "SELECT DISTINCT Item_Name from Add_Items"
Dim ReadData As OleDbDataReader
itemnamecombo.Items.Clear()
ItemChkboxList.Items.Clear()
Try
conn = New OleDbConnection(ConnStr)
conn.Open()
comm = New OleDbCommand(commStr, conn)
ReadData = comm.ExecuteReader
While ReadData.Read
itemnamecombo.Items.Add(ReadData.GetString(0))
ItemChkboxList.Items.Add(ReadData.GetString(0))
End While
Catch ex As Exception
'MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
If itemnamecombo.Items.Count <> 0 Then
itemnamecombo.SelectedIndex = 0
End If
End Sub

Import records from CSV file into SQL Server 2008 R2 using VB .Net 2010

I need to import records from a comma delimited CSV file into an existing table in SQL Server R2 database using Visual Basic .Net 2010. Existing records in the table are to be deleted prior to import. I have been able to create an in-memory temporary DataTable and populate the records from CSV file using TextFieldParser. I have checked it by binding the in-memory DataTable to a DataGridView. But I am clueless in the second part i.e. how to insert records into the SQL table from the in-memory DataTable.
I have done the following:
`Dim TextFileReader As New TextFieldParser("C:\csvtosql\StockVB\VFPFiles\ExpSysusers.csv")
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(",")
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
CurrentRow = TextFileReader.ReadFields() ' Ignore the header
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
Next
End If
Row = TextFileTable.NewRow
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
End If
Catch ex As Exception
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
TextFileReader.Dispose()
DataGridView1.DataSource = TextFileTable
`
Can anybody please help/guide me??
I tried the following code to read the records from the DataTable and insert into the SQL Table. But it seems that only the first record is being added.
For Each TextFileTableDataRow As DataRow In TextFileTable.Rows
Dim Column0 As String = TextFileTableDataRow("Column0")
Dim Column1 As String = TextFileTableDataRow("Column1")
Dim Column2 As Int16 = TextFileTableDataRow("Column2")
Dim Column3 As Boolean = TextFileTableDataRow("Column3")
Dim strSqlQry As String = "INSERT INTO Personnel (Operator,OpPassword,SecurityLevel,Active) VALUES (#Operator,#OpPassword,,#SecurityLevel,#Active)"
Dim SqlconnectionString As String = gcconnect
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(strSqlQry, connection)
' create command objects and add parameters
With cmd.Parameters
.AddWithValue("#Operator", Column0)
.AddWithValue("#OpPassword", Column1)
.AddWithValue("#SecurityLevel", Column3)
.AddWithValue("#LoggedOn", Column7)
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
'--Update the original SQL table from the datatable
Dim iRowsInserted As Int32 = adapter.Update(TextFileTable)
End Using
Next
I am getting the following error:
"Violation of PRIMARY KEY Constraint 'PK_Personnel'. Cannot insert duplicate key in object 'dbo.Personnel'."

VB.NET Insert DataGridView contents into Database

Problem:
I need to dump the contents of my DataGridView into a SQL Server Database Table. I've got the datagridview loading fine, no problems there. I'm just not familiar enough with VB.NET to understand how to get that data into a DB table.
Code: (so far)
Dim connection As New Data.SqlClient.SqlConnection
Dim dataAdapter As New Data.SqlClient.SqlDataAdapter
Dim command As New Data.SqlClient.SqlCommand
Dim dataSet As New Data.DataSet
connection.ConnectionString = "Server= server; Database= DB; integrated security=true"
command.CommandText = "INSERT INTO <table> (Col1, Col2, Col3, Col4) VALUES (#Name, #Property, #Value, #Date)"
dataAdapter.InsertCommand.Parameters.Add("#ServerName", SqlDbType.VarChar)
dataAdapter.InsertCommand.Parameters.Add("#Property", SqlDbType.VarChar)
dataAdapter.InsertCommand.Parameters.Add("#Value", SqlDbType.VarChar)
dataAdapter.InsertCommand.Parameters.Add("#CaptureDate", SqlDbType.DateTime)
For i As Integer = 0 To DataGridView.Rows.Count - 1
dataAdapter.InsertCommand.Parameters(0).Value = dgvServerConfig.Rows(i).Cells(0).Value
dataAdapter.InsertCommand.Parameters(1).Value = dgvServerConfig.Rows(i).Cells(1).Value
dataAdapter.InsertCommand.Parameters(2).Value = dgvServerConfig.Rows(i).Cells(2).Value
dataAdapter.InsertCommand.Parameters(3).Value = dgvServerConfig.Rows(i).Cells(3).Value
Next
connection.Open()
command.Connection = connection
dataAdapter.SelectCommand = command
What am I missing here? Nothing is getting inserted into my table. Any help would be appreciated. Like I said, I'm not very familiar with VB so take it easy on me.
Well, you need to execute the command, not simply add to the DataAdapter
Also, as it coded now, you don't need the DataAdapter at all.
Dim connection As New Data.SqlClient.SqlConnection
Dim command As New Data.SqlClient.SqlCommand
connection.ConnectionString = "Server= server; Database= DB; integrated security=true"
command.CommandText = "INSERT INTO <table> (Col1, Col2, Col3, Col4) VALUES (#Name, #Property, #Value, #Date)"
command.Parameters.Add("#ServerName", SqlDbType.VarChar)
command.Parameters.Add("#Property", SqlDbType.VarChar)
command.Parameters.Add("#Value", SqlDbType.VarChar)
command.Parameters.Add("#CaptureDate", SqlDbType.DateTime)
connection.Open()
command.Connection = connection
For i As Integer = 0 To DataGridView.Rows.Count - 1
command.Parameters(0).Value = dgvServerConfig.Rows(i).Cells(0).Value
command.Parameters(1).Value = dgvServerConfig.Rows(i).Cells(1).Value
command.Parameters(2).Value = dgvServerConfig.Rows(i).Cells(2).Value
command.Parameters(3).Value = dgvServerConfig.Rows(i).Cells(3).Value
command.ExecuteNonQuery()
Next
However this calls the database to insert one row at a time. I think it is better to look at the SqlDataAdapter.Update method that resolves the insert/update work with just one call.
Using the SqlDataAdapter.Update method, requires that you save in a global variable the Adapter used at the moment in which you have filled the DataGridView and add a SqlCommandBuilder that generates for you the InsertCommand, UpdateCommand and DeleteCommand
' At form loading'
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("SELECT COL1, COL2,COL3,COL4 FROM TABLE", connection)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DataGridView.DataSource = myTable
....
' at grid save'
Dim myTable = CType(DataGridView.DataSource, DataTable)
adapter.Update(myTable)
For each object in your GridView, you need to find it and determine its value. So for example,
DropDownList ddlToLoc = (DropDownList)gvMovesMod.Rows[0].FindControl("ddlToLoc");
Then, determine ddlToLoc's SelectedValue and insert to database
You can call: command.ExecuteNonQuery to insert data to the DB.
More info here
TRY THIS METHOD
For index As Integer = 0 To DataGridView1.RowCount - 1
Dim connectionString = "Data Source=localhost;port=3306;Initial Catalog=hasna;User Id=root;password=''; Convert Zero Datetime=True"
Dim query0 = "insert into itemledgerfinal(Date,BillDate,BillNo,ItemName,GST,Rate,MRP,TotalQty,PurchaseRate,WholesaleRate,Total,Type,OpeningBalance,Purchase,Sale,ClosingBalance,ID) values(#Date,#BillDate,#BillNo,#ItemName,#GST,#Rate,#MRP,#TotalQty,#PurchaseRate,#WholesaleRate,#Total,#Type,#OpeningBalance,#Purchase,#Sale,#ClosingBalance,#ID)"
Dim connection0 As New MySqlConnection(connectionString)
Dim command0 As New MySqlCommand(query0, connection0)
command0.Parameters.AddWithValue("#Date", DataGridView1.Rows(index).Cells(0).Value)
command0.Parameters.AddWithValue("#BillDate", DataGridView1.Rows(index).Cells(1).Value)
command0.Parameters.AddWithValue("#BillNo", DataGridView1.Rows(index).Cells(2).Value)
command0.Parameters.AddWithValue("#ItemName", DataGridView1.Rows(index).Cells(3).Value)
command0.Parameters.AddWithValue("#GST", DataGridView1.Rows(index).Cells(4).Value)
command0.Parameters.AddWithValue("#Rate", DataGridView1.Rows(index).Cells(5).Value)
command0.Parameters.AddWithValue("#MRP", DataGridView1.Rows(index).Cells(6).Value)
command0.Parameters.AddWithValue("#TotalQty", DataGridView1.Rows(index).Cells(7).Value)
command0.Parameters.AddWithValue("#PurchaseRate", DataGridView1.Rows(index).Cells(8).Value)
command0.Parameters.AddWithValue("#WholesaleRate", DataGridView1.Rows(index).Cells(9).Value)
command0.Parameters.AddWithValue("#Total", DataGridView1.Rows(index).Cells(10).Value)
command0.Parameters.AddWithValue("#Type", DataGridView1.Rows(index).Cells(11).Value)
command0.Parameters.AddWithValue("#OpeningBalance", DataGridView1.Rows(index).Cells(12).Value)
command0.Parameters.AddWithValue("#Purchase", DataGridView1.Rows(index).Cells(13).Value)
command0.Parameters.AddWithValue("#Sale", DataGridView1.Rows(index).Cells(14).Value)
command0.Parameters.AddWithValue("#ClosingBalance", DataGridView1.Rows(index).Cells(15).Value)
command0.Parameters.AddWithValue("#ID", DataGridView1.Rows(index).Cells(16).Value)
connection0.Open()
command0.Connection = Connection
command0.ExecuteNonQuery()
Next

Resources