I am trying to UPDATE database table rows using SQLCommandBuilder with datatable rows using the following test code. One table with a primary key column and one datatable to keep it simple.
Using the following code, the dbo.Dogs2 table is "appended" with the datatable rows - therefore doubling the number of rows rather than just updating the changed row(s)
If I add the code table.AcceptChanges() just before the Dim builder As New SqlCommandBuilder(adapter), the database table dbo.Dogs2 remains unchanged.
If I add the code table.AcceptChanges() just before the adapter.Update(table), the database table dbo.Dogs2 remains unchanged.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' dbo.Dogs2 database table columns are exactly like datatable columns with exception of dog names
' only UPDATING the "Name" field (no Inserts or deletes)
' orginal dog names "Name" in Dogs2.dbo are Sharpy, Bully, Shep, Charlie, and Yorky
' new dog names "Name" in Dogs2.dbo are June, Tucker, Maggie, Charles, and Candy
' Dex_Row_Id is the primary key with Identity Increment set to 1
' Create a DataTable with five columns.
'
Dim table As New DataTable()
table.Columns.Add("Weight", GetType(Integer))
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Breed", GetType(String))
table.Columns.Add("Size", GetType(Char))
table.Columns.Add("Date", GetType(DateTime))
table.Columns.Add("Dex_Row_Id", GetType(Integer))
'
' Add data to the DataTable
'
AddDogRow(table, 57, "June", "Shar Pei")
AddDogRow(table, 130, "Tucker", "Bullmastiff")
AddDogRow(table, 92, "Maggie", "Anatolian Shepherd Dog")
AddDogRow(table, 25, "Charles", "Cavalier King Charles Spaniel")
AddDogRow(table, 7, "Candy", "Yorkshire Terrier")
ShowResult(table) 'displays datatable correctly (this is a DevExpress.com Reference/Extension)
'
' Create new SqlConnection, SqlDataAdapter, and builder.
'
Dim cnString As String = "<<<SQLConnectionString>>>"
'
Using cnSQL1 As New SqlConnection
cnSQL1.ConnectionString = cnString
Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", cnSQL1)
ShowResult(table) 'displays datatable
Dim builder As New SqlCommandBuilder(adapter)
adapter.UpdateCommand = builder.GetUpdateCommand()
builder.RefreshSchema()
Using New SqlCommandBuilder(adapter)
'
' Fill the DataAdapter with the values in the DataTable.
'
adapter.Fill(table)
ShowResult(table) 'displays datatable + original table data
' Open the connection to the SQL database.
'
cnSQL1.Open()
' Update the SQL database table with the values.
'
adapter.Update(table)
' dbo.Dogs2 now has 10 rows (the 5 rows from the dataset + the original 5 rows)
End Using
End Using
End Using
End Sub
You are using incorrectly the adapter. You should first load the rows from the database, then update the retrieved rows and finally call the update.
' REMOVE THE CODE BEFORE THIS '
' Create new SqlConnection, SqlDataAdapter, and builder.'
Dim cnString As String = "<<<SQLConnectionString>>>"
Dim table = New DataTable() ' Leave it emtpy and without schema'
Using cnSQL1 As New SqlConnection
cnSQL1.ConnectionString = cnString
Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", cnSQL1)
Dim builder As New SqlCommandBuilder(adapter)
adapter.UpdateCommand = builder.GetUpdateCommand()
' no need of this -> builder.RefreshSchema()'
Using New SqlCommandBuilder(adapter)
adapter.Fill(table)
ShowResult(table) 'displays original table data'
' no need of this -> cnSQL1.Open()'
' NOW YOU COULD CHANGE THE ROWS, FOR EXAMPLE'
table.Rows(0)("Weight") = 99
' Update the SQL database table with the values.'
adapter.Update(table)
End Using
End Using
End Using
When you pass an existing table to the Fill method of the Adapter, the existing record are not removed and thus your table is filled with data from the database and from your manual creation of the table (Of course the Adapter build for you the table columns. Moreover, the rows added manually to your table are marked with the DataRowState.Added while the row modified by your code will be marked with the DataRowState.Changed. This state helps the Update command to decide which action to perform on every row present in the table (Of course the rows that are not changed maintain the initial DataRowState.Unchanged
Finally, calling AcceptChanges doesn't mean that the rows will be updated on the database table. Only the DataRowState flag is reset to the DataRowState.Unchanged
Related
I'm trying to insert data into a database with an autonumber in MS Access as primary key. I get an error saying "Number of query values and destination fields are not the same. The data types in MS Access are Autonumber (I didn't include it in the INSERT statement), String (#OrderNo), String (#Product), Number (#Qty), and Date (#TDate). Here's the image:
Here's my code:
For Each row As DataGridViewRow In DataGridView1.Rows
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Inventory.accdb;"
Using conn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert into Table1 Values(#OrderNo, #Product, #Qty, #TDate)", conn)
cmd.Parameters.AddWithValue("#OrderNo", TxtOrder.Text.ToString)
cmd.Parameters.AddWithValue("#Product", row.Cells("Product").Value)
cmd.Parameters.AddWithValue("#Qty", row.Cells("Qty").Value)
cmd.Parameters.AddWithValue("#TDate", Date.Now.ToString("MM/dd/yyyy"))
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
You need to change your sql to "Insert into Table1 (OrderNo,Product,Qty,TDate) Values(#OrderNo, #Product, #Qty, #TDate)".
The following code works for me.
DataGridView1.AllowUserToAddRows = False
For Each row As DataGridViewRow In DataGridView1.Rows
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=...;"
Using conn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert into Table1 (OrderNo,Product,Qty,TDate) Values(#OrderNo, #Product, #Qty, #TDate)", conn)
cmd.Parameters.AddWithValue("#OrderNo", TxtOrder.Text.ToString)
cmd.Parameters.AddWithValue("#Product", row.Cells("Product").Value)
cmd.Parameters.AddWithValue("#Qty", row.Cells("Qty").Value)
cmd.Parameters.AddWithValue("#TDate", Date.Now.ToString("MM/dd/yyyy"))
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
Well, I think we dealing with a bit of a chicken and a egg problem here?
I mean, how did the grid get created?
How and where did you setup the columns in the grid?
lets drop a data grid view into a form. Drop in a button.
We have this code to load up the grid:
Private Sub HotelGridEdit_Load(sender As Object, e As EventArgs) Handles Me.Load
LoadGrid()
End Sub
Sub LoadGrid()
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"SELECT ID, FirstName, LastName, City, HotelName, Description, Active FROM tblHotelsA
ORDER BY HotelName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
DataGridView1.DataSource = rstData
End Using
End Using
End Sub
So, now we have this:
Now, in a above, I can cursor around - make any edits I want.
I can also type in on the bottom blank row to add new rows.
I can click on the left side recordselector, and hit delete key.
Now, to save my edits, save my addtitions, and save my deletes?
I have the one button at the top, and this code works to do all updates, all addtitions, and all deletes.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' save all edits, and new rows, and deletes
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"SELECT ID, FirstName, LastName, City, HotelName, Description, Active FROM tblHotelsA"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim da As New OleDbDataAdapter(cmdSQL)
Dim daC As New OleDbCommandBuilder(da)
da.Update(DataGridView1.DataSource)
End Using
End Using
End Sub
So, not a lot of code.
In fact, often using a data table is a lot less work, since you don't have to mess with all those parameters anyway - even if your data grid was somehow not feed from the database. But, if you feeding the "grid" from the database, then really, you can just add rows - and then write some code to send the changes back to the database with the above code. And if you want to start out with a blank grid - not show previous rows, then just add to your sql like this:
SELECT * from tblHotels WHERE ID = 0 Order by Hotelname
Use above to create a data table without any rows but STILL bind that to the grid, and thus once again, to add, or delete rows, you just edit and add them, and again the SAME code I had above will work to save edits, deletes and additions.
I am attempting to make a small application allowing users to read the content of a table describing the inventory of a warehouse, search depending on 2 rows indicating which warehouse the item resides in and by it's assigned barcode which i already managed to get to work by using a binding source, and a datagrid view, updating the view trough a query taking the barcode and location as strings from two boxes.
The second part i would need for this application to suit my basic objective would be to have a way to add new lines and store them into the original table on the database so users could add the new items independently from the warehouses directly.
So far i have encountered 2 issues: i need a primary key that would represent a sequential ID but i do not know how to produce a sequentially incrementing ID, i manage to get the first addition ID by using a top 1 order by desc query combination but the data does not get updated after adding the new line, producing an error since it tries to add another line with the same value for the primary key.
The second issue i am encountering is: the gridview gets altered accordingly to the data i input in the textboxes i set up to gather the various values for the table but the table on the database itself is not showing any change, keeping only the test data i inputted at it's creation.
Public Class AddItems
Private Sub AddItems_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MagazzinoDataSet.LastUsedID' table. You can move, or remove it, as needed.
Me.LastUsedIDTableAdapter.LastUsedID(Me.MagazzinoDataSet.LastUsedID)
'TODO: This line of code loads data into the 'MagazzinoDataSet.Stock' table. You can move, or remove it, as needed.
Me.StockTableAdapter.Fill(Me.MagazzinoDataSet.Stock)
'TODO: This line of code loads data into the 'MagazzinoDataSet.AddWarehouseList' table. You can move, or remove it, as needed.
Me.AddWarehouseListTableAdapter.AddWarehouseList(Me.MagazzinoDataSet.AddWarehouseList)
'TODO: This line of code loads data into the 'MagazzinoDataSet.WarehouseList' table. You can move, or remove it, as needed.
Me.WarehouseListTableAdapter.Fill(Me.MagazzinoDataSet.WarehouseList)
'TODO: This line of code loads data into the 'MagazzinoDataSet.Stock' table. You can move, or remove it, as needed.
Me.StockTableAdapter.Fill(Me.MagazzinoDataSet.Stock)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim R As DataRow = MagazzinoDataSet.Tables("Stock").NewRow()
R("Supplier") = Supplier.Text
R("Producer_code") = ProducerCode.Text
R("Barcode") = Barcode.Text
R("Comp_name") = ComponentName.Text
R("Warehouse") = Warehouse.Text
R("Internal_Code") = InternalCode.Text
R("Description_IT") = ITDescr.Text
R("Description_EN") = ENDescr.Text
'R("ID") = NextID.SelectedValue <- this would be an hidden uneditable multibox containing the product of the query finding the next value to be inserted in the table (basically last ID + 1, nothing fancy)"ID" would be the primary key of this table
R("Quantity") = "0"
MagazzinoDataSet.Tables("Stock").Rows.Add(R)
DataGridView1.DataSource = MagazzinoDataSet.Stock
End Sub
End Class
To sum it up:
How would i go about updating the database table to include the new line?
Is there a smart way to find the last value, incrementing it by 1 to have the next value and updating it when inserting a new line, so as to not end up with 2 lines with the same value for primary key, generating an error?
To set an incremental ID in the Db, assuming you have access to SQL Server Management Studio, in Design of the table, for the ID column, in Column Properties, scroll down to Identity Specification and set (is Identity) to Yes.
To add a new row, I use this code:
Using NotesDS As New DataSet
Using NotesDA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = SQLDBConnection, .CommandText = "SELECT * FROM Notes WHERE ID = " & ID}}
NotesDA.Fill(NotesDS, "Notes")
Using NotesDV As New DataView(NotesDS.Tables("Notes"))
Using NoteBuilder As New SqlCommandBuilder(NotesDA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
If NotesDV.Count = 0 Then
Dim NoteDRV As DataRowView = NotesDV.AddNew
NoteDRV.Item("UserName") = UserName
NoteDRV.Item("Note") = Note
NoteDRV.Item("NoteDate") = NoteDate
NoteDRV.Item("CompanyCode") = CompanyCode
NoteDRV.EndEdit()
NotesDA.UpdateCommand = NoteBuilder.GetUpdateCommand
NotesDA.Update(NotesDS, "Notes")
End If
End Using
End Using
End Using
End Using
Obviously, amend to make appropriate for your table and column names.
If you need to retrieve the ID for display, you can add a handler to the Update like:
Public Sub GenericOnRowUpdated(sender As Object, e As System.Data.SqlClient.SqlRowUpdatedEventArgs)
Dim newID As Integer = 0
Dim idCMD As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT ##IDENTITY", SQLDBConnection)
If e.StatementType = StatementType.Insert Then
newID = CInt(idCMD.ExecuteScalar())
e.Row("ID") = newID
End If
End Sub
and use like:
AddHandler NotesDA.RowUpdated, New SqlRowUpdatedEventHandler(AddressOf GenericOnRowUpdated)
NotesDA.Update(NotesDS, "Notes")
NewID = NoteDRV.Item("ID")
EDIT
First Example amended and explained below:
'Declare you connection to the SQL dB. Connection String looks like "Data Source=192.168.71.10\dBName; Initial Catalog=dBName; User ID=USER; Password='PASSWORD!';MultipleActiveResultSets=true" - You may well already have an open connection, and can use that instead. Not sure what your
StockBindingSource is...
Dim oConn As New SqlConnection("CONNECTION STRING")
'Open the connection
oConn.Open()
'Declare Your DataAdapter and initialise using your connection
Dim DA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = oConn, .CommandText = "SELECT * FROM Stock WHERE ID=0"}}
'Declare you DataSet
Dim DS As New DataSet
'Fill Your DataSet with the Stock table from your DataAdapter
DA.Fill(DS, "Stock")
'Declare a DataView for easy use (really the same as using DS.Tables("Stock").DefaultView)
Dim DV As New DataView(DS.Tables("Stock"))
'Declare a CommandBuilder and initialise with your DataAdapter. This will now watch for changes made to your data and build the appropriate SQL UPDATE/INSERT/DELETE command. the "[" and "]" are in case any column names use reserved words
Dim Builder As New SqlCommandBuilder(DA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
'Decalre a DataRowView for data population, based on your DataView table structure
Dim R As DataRowView = DV.AddNew()
'Populate the fileds with your Form data
R("Supplier") = Supplier.Text
R("Producer_code") = ProducerCode.Text
R("Barcode") = Barcode.Text
R("Comp_name") = ComponentName.Text
R("Warehouse") = Warehouse.Text
R("Internal_Code") = InternalCode.Text
R("Description_IT") = ITDescr.Text
R("Description_EN") = ENDescr.Text
R("Quantity") = "0"
'Notify that the edit has finished
R.EndEdit()
'Get the SQL command from the CommandBuilder
DA.UpdateCommand = Builder.GetUpdateCommand()
'Execute the update (in this case it will be an INSERT)
DA.Update(DS, "Stock")
please advise; what is wrong in this code ?
giving below error ... Column 'xxxx' does not belong to underlying table ''.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim connStr As String = ConfigurationManager.ConnectionStrings("FBB-DSL-DBConnectionString").ConnectionString
Dim tablex As New DataTable()
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand("sp_columns", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#table_name", "tbl_EmpRecords")
' get the adapter object and attach the command object to it
Using ad As New SqlDataAdapter(cmd)
' fire Fill method to fetch the data and fill into DataTable
ad.Fill(tablex)
End Using
End Using
End Using
'Creating DataView
Dim view As New DataView(tablex)
Dim dt As DataTable = view.ToTable(False, "COLUMN_NAME" )
CheckBoxList1.DataSource = dt
CheckBoxList1.DataBind()
End If
End Sub
The system defined stored procedure sp_columns produces a datatable where each row contains the schema details of the columns in the tbl_EmpRecords.
This means that the columns present in this tablex are the following:
TABLE_QUALIFIER,
TABLE_OWNER,
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
TYPE_NAME,
PRECISION,
LENGTH,
SCALE,
RADIX,
NULLABLE,
SQL_DATA_TYPE,
SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH,
ORDINAL_POSITION,
IS_NULLABLE,
SS_DATA_TYPE
See the MSDN docs about sp_columns for the meaning of each column.
So, there is no column named XXXXXX and this is exactly what the error tells you. If you really want to create a new datatable with only one column then your XXXXX field should be one of the above names.
' This will return a new table with only one column named COLUMN_NAME'
' The table will contain all the column names of the table tbl_EmpRecords'
Dim dt As DataTable = view.ToTable(False, "COLUMN_NAME")
Instead, if you are trying to sort the tbl_EmpRecords using someone of the fields defined in that table (IE, empName, HireDate etc....) then you have to use a different approach for your query.
....
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand("select * from tbl_EmpRecords", conn)
Using ad As New SqlDataAdapter(cmd)
ad.Fill(tablex)
End Using
End Using
End Using
....
then you can proceed with the DataView code.
However, it is always better to query the database to retrieve only the data you are interested in.
So, if you need only the field XXXXX then just use the query
select XXXXX from tbl_EmpRecords
and probably you can ask the database to sort that record for you with
select XXXXX from tbl_EmpRecords ORDER BY XXXXX
removing all the DataView code.
The stored procedure:
select sum(column)
from table
returns only one column, one row from a given table.
In the vb.net form I don't want to use a datagridview to get the sum in a one cell table, I want to get the sum in a simple combobox. It's possible?
...
Dim cmd As New SqlCommand("stored_procedure", con)
con.Open()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#parameter", SqlDbType.VarChar).Value = TextBox1.Text
Dim dtc As New DataTable
dtc.Load(cmd.ExecuteReader())
con.Close()
DataGridView1.DataSource = dtc ' this is working
ComboBox1.DataSource = dtc ' for this I get System.Data.DataRowView in combo
...
Thank you
You can use
ComboBox1.text = dtc.Rows(0).Item(0).tostring
or a combination of combobox1.clear and combobox1.add
I have 37 columns in DataGridView (Access database), except the first column, every cell in 50x36 table is changeable with mouse click (click on cell gives value of "X", another click ""). Is it possible to completely update Access database from DataGridView, basically overwrite Access database table with DataGridView data table?
I don't know how to do that differently, since there are changes all over the place in one session, not only in one row of the database, so I really would know how to implement INSERT into all that.
DatagridView is populated with this code.
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\PD_Z.mdb"
Dim SQLString As String = "SELECT * FROM ZARADE"
Dim OleDBConn1 As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(ConnString)
Dim DataSet1 As New DataSet()
Dim OleDbDataAdapter1 As System.Data.OleDb.OleDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQLString, OleDBConn1)
OleDBConn1.Open()
OleDbDataAdapter1.Fill(DataSet1, "ZARADE")
DataGridView1.DataSource = DataSet1.Tables("ZARADE")
DataGridView1.Columns.Remove(DataGridView1.Columns(0).Name)
OleDBConn1.Close()
You could use the OleDbCommandBuilder class to build your queries automatically. But it generates only single table commands.
Since you already have the OleDbDataAdapter instance, use the same to update the database.
Sample code:
Dim cb As New OleDbCommandBuilder(OleDbDataAdapter1);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
OleDbDataAdapter1.Update(DataSet1.Tables("ZARADE"))