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.
Related
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 checked whether a value exists
Dim connectionString = [connection string ]
Using exist As New SqlConnection(connectionString)
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Employees WHERE WorkEmail = #WorkEmail", exist)
cmd.Parameters.AddWithValue("#WorkEmail", DataObjects.Contacts.ElectronicAddress.Email)
If cmd.ExecuteScalar > 0 Then
//return row so that I can grab values from it, given column names
How would I go about doing that commented section on the last line?
You should execute your command and then check if it returned any rows.
See Retrieving Data Using a Data Reader
An excerpt slightly tweaked for your use case:
Private Sub HasRows(ByVal connection As SqlConnection)
Using connection
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Employees WHERE WorkEmail = #WorkEmail", connection)
cmd.Parameters.AddWithValue("#WorkEmail", DataObjects.Contacts.ElectronicAddress.Email)
connection.Open()
Using reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
REM Your code to pull the data you want from the returned data goes here
End While
End Using
End Using
End Using
End Sub
In the future try looking through the Microsoft Documents. You will usually find what you need there.
Thanks I used the MAX statement and it doesn't return an error but still don't understand why it isn't working. My code is shown below:
Protected Sub txtuserID_TextChanged(sender As Object, e As System.EventArgs) Handles txtuserID.TextChanged
Dim strConnection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\LostPropertyProject\App_Data\LostPropertyDatabase.mdf;Integrated Security=True;User Instance=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim comm As New SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM tblUser"
comm.Connection = con
Dim MaxUserID As Object = comm.ExecuteScalar()
con.Close()
End Sub
Also, I want the userID to be displayed in the textbox as soon as the page loads. How do I go about doing that? and thank you to everyone who replied to my question :) much appreciated
SELECT MAX(UserId) FROM User
This will give you the latest user id from the table.
Ive seen tutorials on the net on how to do it, but the tutorial is not applicable on the program that I wish to do. The tutorial tells you to add 4 navigation buttons so that you can navigate the database(first, last, back, and forward). Then an update and delete button.
But if this is what I will do, it would take 10 years to navigate the database and update a record.
Now, what I want to do is just for the user to input a unique ID and click search button(which I have already done). Then the update would be easier. How can I update or delete a record using this method?
Something along these lines:-
Dim cnn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyDatabase.mdb;User Id=admin;Password=;")
Dim cmd As New OleDbCommand
Dim _ID as Integer=1
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM blah WHERE primarykey=" & _ID
Using cnn
cnn.open()
cmd.ExecuteNonQuery()
End Using
Imports System.Data.OleDb
Dim conn2 As OleDbConnection
Dim DeleteData As OleDbCommand
conn2 = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="table location here";Persist Security Info=False;")
sql1 = "DELETE * FROM [Audit Log]" ' query for deleting data
conn2.Open() ' openning second connection for clearing purpose
DeleteData = New OleDbCommand(sql1, conn2) 'second connection to remove information from the old table
DeleteData.ExecuteNonQuery()
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.