I'm new to vb.net and having quite a challenge with updating a field in a table using the For...Next construct on a data set. Sample code below - can anyone tell me what I'm missing? I know this particular example could be accomplished with a simple SQL update statement, but the actual use for what this code will become requires stepping through each record in the dataset. The example below is just a simple one to let me get the procedure down. Note that this runs without an exception, but just doesn't change the data in the table.
Help! :)
Dim objConn As SqlConnection = New SqlConnection("Data Source=DALLAS\;Initial Catalog=Adaptive;Integrated Security=True")
Dim selectCMD As SqlCommand = New SqlCommand("SELECT * from dwbprocref", objConn)
selectCMD.CommandTimeout = 30
Dim custDA As SqlDataAdapter = New SqlDataAdapter
custDA.SelectCommand = selectCMD
Dim custCB As SqlCommandBuilder = New SqlCommandBuilder(custDA)
custCB.QuotePrefix = "["
custCB.QuoteSuffix = "]"
Dim dRow As DataRow
Dim dTable As DataTable
objConn.Open()
Dim custDS As DataSet = New DataSet
custDA.Fill(custDS, "dwbprocref")
For Each dRow In custDS.Tables(0).Rows
If dRow.Item("pr_format") = "MDV" Then
dRow.Item("pr_tester") = "X"
End If
custDS.AcceptChanges()
Next
custDA.Update(custDS, "dwbprocref")
objConn.Close()
You're calling AcceptChanges. This marks all of the rows as being unmodified, so they are never updated in the database. Remove this call and you should be good.
Related
hi I have a somewhat bizarre problem
When I go to add the table from sql on datagridview like:
Dim Connection As New SqlConnection("SERVER=*******;DATABASE=********;USER=sa;PWD=********")
Dim cmd As SqlCommand = New SqlCommand(query1, Connection)
Dim da As New SqlDataAdapter(cmd)
Dim commandbuilder = New SqlCommandBuilder(da)
Dim ds = New DataSet()
da.Fill(ds)
dtgMain.AutoGenerateColumns = True
dtgMain.DataSource = ds.Tables(0)
Nothing is displayed in the datagridview.
If I count the rows and columns imported:
MsgBox(dtgMain.Columns.Count)
MsgBox(dtgMain.Rows.Count)
It correctly returns both.
Even if I preview the ds.tables I can see the table correctly
Tips??
Attempting to fill a data table using SqlDataAdapter with a WHERE clause but it returns nothing. The SQL command itself returns data from SSMS and removing just the WHERE clause in code fills data table as expected.
Dim adapter As New SqlDataAdapter
Dim datatable As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
adapter = New SqlDataAdapter("SELECT * FROM [MyProjectDtbl] WHERE zipcode = 22021", cnn)
adapter.Fill(datatable)
adapter.Dispose()
End Using
Digging through the Select command EventSink, I found:
Unable to cast object of type 'System.Data.SqlClient.SqlInternalConnectionTds' to type 'System.Data.SqlClient.SqlInternalConnectionSmi'
Try it with parameters.
Private Sub OPCode()
Dim dt As New DataTable
Using cnn As New SqlConnection(connectionString),
cmd As New SqlCommand("SELECT * FROM [MyProjectDtbl] WHERE zipcode = #zip", cnn)
cmd.Parameters.Add("#zip", SqlDbType.Int).Value = 22021
cnn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Debug.Print(dt.Rows.Count.ToString)
End Sub
Would there be a chance to solve this problem? Once that I inserted a data from the Database, I wanted to update my DataGridView from the other form. Clearly the datagridview has to update as it SELECT on the table of the Database. But once that I updated the datagridview, I tried closing the system from running and restart it again. But when I checked there it didn't update. It goes like the usual datas that is from the Database. However my database is well updated and the data I inserted from the TextBoxes was there too.
Private Sub updateBtn_Click(sender As Object, e As EventArgs) Handles updateBtn.Click
Dim newtable = New DataTable()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "C:\Users\Anthony\Desktop\thesis\DATABASE\BookLists.accdb"
connString = provider & datafile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
Try
str = "Select * from TVL12"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Dim da As OleDbDataAdapter = New OleDbDataAdapter()
da.SelectCommand = cmd
da.Fill(newtable)
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
TVL12.BookListTVL.DataSource = newtable
End Sub
Here's the code for Updating the DataGridView. Anyone had any ideas why does it only Temporarily updates the DataGridView?
Here is my general understanding of database from what I read so far: Save / Update / Delete to pre-existing file made that binds to form thru SQL.
Here is what I am trying to do - I have a pre-made Data Table in Form with all columns defined. Once app is closed or certain functions ran, I need that data to be saved / updated in SQL (on local). Once app is open I need all that data to be preserved.
So far I have NOT found a single solution to it anywhere most refer to binding to an existing file. When I worked with Excel data transfer cells had to be defined and referenced in form for population.
My assumption is when a database from VB.NET is used, table with values can be created automatically saved/loaded/updated. However this is only my assumption since I never worked with SQL before. I am not sure if I need to manage an actual database file I created with all the values and then bind them to data table. For example DataTable cell XX to database column XX.
Here is what I done so far I have created database and added to my project. I tried few codes and I keep getting Dataset Empty even though there is Data in Table I tried to use DataTable as well but so far nothing has worked.
Please suggest on what I am doing wrong also additional information regards to databases will be great. As per previous I do know how binding works when actual file exist. But creating and managing is confusing to me since I keep thinking there should be a binding file.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "SELECT BN FROM DataTable" ' BN is my column name and DataTable is the name of my Table where data gets populated. This is also confusing to me How does it know which value is what? Is there are space/word/characters requirements?
' adapter.TableMappings.Add("DataTable", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds)
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
Code I use to Create /Save Database. As per previous all columns/formats are pre-made, loaded.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "Select BN FROM DataTable"
adapter.TableMappings.Add("BN", sql)
If DataTable.RowCount > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf DataTable.RowCount = 0 Then
MsgBox("Empty data")
End If
End Sub
Please see more info below:
Data Table columns/format are structured for visual representation.
When User start the App Database can be empty/Can contain Values.
When users Runs certain function Closes App values are save and only values.
If I would you an MS Access I would structure same table/values and cross reference it with form values. Form Values come from outside source and Format/Qty is always known.
Hope this helps to have a cleaner look at my issue. Perhaps SQL is not a right choice for me? Does SQL needs to be build before value manipulation.
UPDATE: I Got rid of the Invalid Object error. Table had to be created 1st as I originally thought. However, My DataSet always comes up as EMPTY when I try to save... Cells do contain BN data as" 1,2, ....) Even if I to remove "If" logic Save and Load table comes out as empty. Something does load because when I try to ADD BN it tells me binding bla bla bla(different issue)
CODE:
Private Sub SaveData()
Dim connetionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Dim sql As String = "SELECT BN FROM DataTable_d"
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet()
adapter.TableMappings.Add("BN", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
UPDATE: I got all the things working but I can't save multiple rows..... Could really use some help
In your SQL query remove WHERE DataTable ='. This statement is looking for a column name DataTable which I assume does not exist. The WHERE clause is used to help filter your query. You only use WHERE on column names in your table.
For instance:
SELECT BN FROM DataTable
will return all values from the BN column from DataTable.
Note that if you have multiple columns, the above query will still only return values from BN.
SELECT * FROM DataTable
will return every value in DataTable.
A helpful site to look at documentation for SQL is w3schools.
Let's start with just displaying some data. Add a DataGridView to a Form. You can call LoadData() from a button. I am not very sure of you connection string but give it a try.
Private dt As DataTable
Private sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Private Sub LoadData()
'***EDIT*** Add instantiation line
dt = New DataTable()
'The Using...End Using blocks will close and dispose your database objects
'even if there is an error
Using cn As New SqlConnection(sql)
'You can pass the command text and the connection directly to the constructor
'In the select statement use the actual names of the field and table as they appear in the database.
Using cmd As New SqlCommand("Select BN From [Insert the name of the table in the database]", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
This is the simplest way I can think of to display data. We will proceed with changing the data once this works. If you get an error on cn.Open() We will have to work on the connection string.
****EDIT****
Private Sub TestConnection()
Dim sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Using cn As New SqlConnection(sql)
cn.Open()
End Using
End Sub
I have two update sql statements for two SqlCommand object to update one DataTable with DataSet object to One Source Table. When I click on update button that's update only the first one and the second SqlCommand Object doesn't work. What's it? DataTable didn't support two Command object at one time? I write as follow:
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=usr;Password=pwd")
Dim dadStockInfo As New SqlDataAdapter
Dim dsStockInfo As New DataSet
Dim transStockInfo As SqlTransaction = Nothing
Try
conxMain.Open()
transStockInfo = conxMain.BeginTransaction()
dadStockInfo.SelectCommand = New SqlCommand("SELECT * FROM Stock", conxMain, transStockInfo)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadStockInfo)
dadStockInfo.FillSchema(dsStockInfo, SchemaType.Source, "Stock")
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
Dim cmdStockUpdateCmd As SqlCommand = Nothing
cmdStockUpdateCmd = New SqlCommand("UPDATE Stock SET StockCode= 'TestCode' WHERE StockID = 4", conxMain, transStockInfo)
dsStockInfo.Tables("Stock").Columns("StockID").ReadOnly = False
dadStockInfo.UpdateCommand = cmdStockUpdateCmd
//dadStockInfo.Update(dsStockInfo, "Stock") [I have already tried this but did not work]
Dim cmdStockUpdateCmd1 As SqlCommand = Nothing
cmdStockUpdateCmd1 = New SqlCommand("UPDATE Stock SET StockCode= 'Test-Code2' WHERE StockID = 1", conxMain, transPurchaseInfo)
dadStockInfo.UpdateCommand = cmdStockUpdateCmd1
dadStockInfo.Update(dsStockInfo, "Stock")
transStockInfo.Commit()
Can't I use like above? please point me out !
Hello ! Help me! F1 :)
The way you use it you shouln't need the dataadapters and datasets...
You just execute 2 update statements.
You can just do
cmdStockUpdateCmd1 = New SqlCommand("UPDATE Stock SET StockCode= 'Test-Code2' WHERE StockID = 1", conxMain, transPurchaseInfo)
cmdStockUpdateCmd1.ExecuteNonQuery();
Datasets and dataadapters are for getting data to the client.
Changing data on the client side and then sending the modifications to the server.
You are making your changes directly on the server with SQL.