Execute two sql commands related in VB.NET - sql

I'm trying to execute two related sql commands in a single function top update my column xamlfile by a new xamlfile --> u
Here's my code
Public Shared Function updatetest()
Dim c As SqlConnection = openConnection("Data Source=GENIOP40;Initial Catalog=TF5100_new;Integrated Security=true")
Dim c2 As SqlConnection = openConnection("Data Source=GENIOP40;Initial Catalog=TF5100_new;Integrated Security=true")
Dim cmd As New SqlCommand("SELECT xamlfile, id_wkfw_task from WKFW_Tasks Where xamlfile like '%ExecuteTask%' order by name", c)
Dim rd As SqlDataReader = executereader(cmd)
Dim listxaml As New List(Of String)
While rd.Read
Dim u As String = GetString(rd, "xamlfile")
Dim Id As Guid = GetGuid(rd, "id_wkfw_task")
u = Regex.Replace(u, "(?<=<t[1-2]|:ExecuteTask[^><]+)\bTache", "TaskID")
u = u.Replace("'", "''")
Dim cmd2 As New SqlCommand("UPDATE WKFW_Tasks set xamlfile=#xmlfile where id_wkfw_task=#id_t", c2)
cmd2.Parameters.Add("xmlfile", SqlDbType.NVarChar).Value = u
cmd2.Parameters.Add("id_t", SqlDbType.UniqueIdentifier).Value = Id
cmd2.CommandTimeout = 0
executeNonQuery(cmd2)
c2.Close()
End While
rd.Close()
c.Close()
End Function
My problem is : when I close the reader after the loop, my first command is no more executed, and I need it to be executed so my second command can work, and if I don't close my reader I have an error, any suggestions please ?

Change your initial connectionstring to
Dim c As SqlConnection = openConnection("Data Source=GENIOP40;
Initial Catalog=TF5100_new;Integrated Security=true;
MultipleActiveResultSets=true")
See MSDN on MultipleActiveResultSets
Now you don't need anymore to have the DataReader closed between the calls and you can execute the command using the only one connection. However I recommend to move the creation of the update command and its parameters outside the loop.
Inside the loop just update the parameter values and execute
Dim cmd2 As New SqlCommand("UPDATE WKFW_Tasks set xamlfile=#xmlfile where id_wkfw_task=#id_t", c)
cmd2.Parameters.Add("xmlfile", SqlDbType.NVarChar)
cmd2.Parameters.Add("id_t", SqlDbType.UniqueIdentifier)
While rd.Read
....
cmd2.Parameters("xmlfile")..Value = u
cmd2.Parameters("id_t").Value = Id
executenonquery(cmd2)
End While

Related

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

Update Access database records by column, row known

This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()

Windows Service That reads From one table and inserts into another

I am writing a windows service that will read records from one table and write them to another table. Problem is when i declare cmd = New SqlCommand(l_sSQL) the code stop executing
but the service will still be running. I can insert into the other table using the service but i cant read from the other table.
Code Sample:
Private Sub dbcon()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim x As String
Try
con.ConnectionString = "Data Source=xxxx;Initial Catalog=xxxxx;Persist Security Info=True;User ID=sa;Password=xxxxxxx"
con.Open()
cmd.Connection = con
cmd = New SqlCommand()
Dim i As Integer
l_sSQL = "SELECT * ozekimessageout"
cmd = New SqlCommand(l_sSQL)\\stops executing here
adapter.SelectCommand = cmd
adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
x = (ds.Tables(0).Rows(i).Item(1))
next
End Sub
Please Help....
Don't you need: SELECT * FROM ozekimessageout
Plus: You are 'newing' cmd twice, there is no need.

SQL read data from table in vb

I'm trying to get a single field back from the data. (I am searching by a primary key so I should get 0 or 1 answer). Please help. The table that I am querying has one entry with user = someone, input to several columns with the ans column having "a good answer"
Code:
Dim reader As SqlDataReader
Dim par As SqlParameter
Dim result As String
Dim sqlconn As SqlConnection
sqlconn = New SqlConnection("....")
sqlconn.Open()
Dim sqlcmd As SqlCommand
sqlcmd = New SqlCommand("Select Ans From Test Where User = #auser", sqlconn)
par = New SqlParameter
par.ParameterName = "auser"
par.Value = Textbox1.Text
sqlcmd.Parameters.Add(par)
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
''//output to label
label1.Text = result
You need to read the data reader first to place it on the first row.
So instead of
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
You'd insert the Read() method like so:
reader = sqlcmd.ExecuteReader()
if reader.Read() then '' <<<<< newly inserted code
result = reader.GetString(0)
end if
''// using statement will guarantee the object is closed and disposed
''// even if an exception occurs
Using sqlconn As New SqlConnection("...."), _
sqlcmd As New SqlCommand("Select Ans From Test Where User = #auser", sqlconn)
''// you can create, add, and set the value for a parameter all on one line
sqlcmd.Parameters.Add("#auser", SqlDbType.VarChar, 50).Value = Textbox1.Text
''//wait as long as possible to open the connection
sqlconn.Open()
''// if you're only getting the first column of the first row, use execute scalar
label1.Text = CString(sqlcmd.ExecuteScalar())
End Using