Piping the results of a stored procedure to .NET text box - sql

I have a Winform that simply contains a textbox object, which I'm trying to use as a repository for the results of a T-SQL stored procedure. Here is the code I'm using to connect to the database and run the stored procedure.
The SP seems to be running correctly, however it's not returning the information to the textbox in the way I'm expecting. It's not updating the text property at all.
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Dim reader As SqlDataReader
Try
con.ConnectionString = ("Data Source=" & Utilnamespace.SQLSvr & ";Database=Master" & ";integrated security=SSPI;")
Dim cmd As New SqlCommand("sp_whoisactive", con)
con.Open()
reader = cmd.ExecuteReader()
While reader.Read()
txtSQL.Text = String.Format("{0}", _
reader(0))
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server. " & ex.Message)
Finally
con.Close()
End Try
Return "Done"
End Function
What am I doing wrong here?

Shouldn't you be concatenating?
While reader.Read()
txtSQL.Text += String.Format("{0}", _
reader(0))
End While

Related

VB.net Is possibile ti use a THREAD to speed up a query? (Re-question from #Livio)

I try to ask this question from the user #Livio. Hope that's the right way!
I have a form with 6 textbox. Every textbox Is populated from a query. This took a long time to show the form.
Using a THREAD to speed up the operation Is a good idea?
DBConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & Para1 & "\F5C DRAGG_be.mdb;"
Try
DBConn.Open()
Catch ex As Exception
MsgBox(ex.Message)
MsgBox(ex.ToString)
End Try
RecuperoNPG("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & Para1 & "\F5C DRAGG_be.mdb;")
And the sub where the query phisically is :
Public Function RecuperoNPG(ByVal connString As String) As Integer
Dim NPG As Int32 = 0
Dim sql As String = "SELECT Count(RegProduzione.MATRICOLA) AS C_MATRICOLA FROM RegProduzione WHERE Regproduzione.Data = #" & T_Data_Conv.Text & "#"
Using Conn As New OleDb.OleDbConnection(connString)
Dim Cmd As New OleDb.OleDbCommand(sql, Conn)
Try
Conn.Open()
NPG = Convert.ToInt32(Cmd.ExecuteScalar())
T_MotGiorno.Text = NPG
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return NPG
End Function

Having the ExecuteNonQuery : connection property has not been initialized

I'm trying to delete an entry from my database. But when the ExecuteNonQuery has to do it's job it can't find the enabled connection and give me this error :
System.InvalidOperationException :'ExecuteNonQuery : connection property has not been initialized'
Here is what I did :
Dim delete As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim dt As DataTable
initConnectionDtb(pathDtb)
openConnection()
If TextBox2.Text <> "" Then
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
MsgBox("USER HAS BEEN DELETED")
Else
MsgBox("ERROR")
End If
I could check if it was properly connected to the Database thanks to connectionName.State
I also enterily rewrote the connetion to the database in the function but ExecuteNonQuery still couldn't connect even though the connection was opened
I saw that i'm not the only one on this website but none of the previous answers have helped me.
#Filburt pointed out, how are you assigning your connection to your command object. Here is an example :
Using connection As OleDbConnection = New OleDbConnection(connectionString)
connection.Open()
Dim command As OleDbCommand = New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
End Using
In your code, you need to assign the connection object to your command object. We can't see what code you have in initConnectionDtb(pathDtb) or openConnection()
To adapt this to your code:
delete.Connection = <<your connection object here>>
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
Another note: look into parameterizing your query strings instead of hand stringing the values. This will prevent issues with TextBox2.Text having a value like O'Toole which will cause a syntax error as well as SQL Injection.
Here's what i used to initialize my connection :
Public Function initConnectionDtb(ByVal path As String) As Boolean
initConnectionDtb = True
Connection = New OleDbConnection
Try
Connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;" & "data source= " & path & ";"
Catch ex As Exception
Return False
End Try
End Function
Public Function openConnection() As Boolean
openConnection = True
Try
Connection.Open()
MsgBox(Connection.State) 'to test if my connection really openned in my previous post
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub closeConnection()
If Not IsNothing(Connection) Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
MsgBox(Connection.State)
Connection.Dispose()
Connection = Nothing
End If
End Sub
So far it worked for everything i tried (adding someone to the database for exemple)

Saving data to access not working, despite no errors

Hey I'm trying to use this code to save to my access database and although there are no errors and it says data saved, my access database doesn't receive the new data. What's wrong with it?
Private Sub savenew()
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & dbsource
Dim reader As OleDbDataReader
Dim command As OleDbCommand
Try
conn.Open()
Dim query As String
query = "insert into item(name) values ('" & TextBox4.Text & "')"
command = New OleDbCommand(query, conn)
reader = command.ExecuteReader
MsgBox("data saved")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
(table in my database is called item, and column is called name.)

SQLite in vb 2010

I have, for over a month, tried in vain to resolve this. I am using SQLite and trying to write a simple check to see if i can connect to the database. I found some code here that was supposed to do just that.
Public Function ConnExist(strDB) As Boolean
Dim SQLconnect As New SQLite.SQLiteConnection()
Try
Using Query As New SQLiteCommand()
SQLconnect.ConnectionString = "DataSource=" & strDB & ";Version=3;New=False;Compress=True;"
SQLconnect.Open()
With Query
.Connection = SQLconnect
.CommandText = "SELECT * FROM tbltest"
End With
Query.ExecuteNonQuery()
SQLconnect.Close()
End Using
'SQLconnect.ConnectionString = "Data Source=" & strDB & ";Version=3;New=False"
'SQLconnect.Open()
'SQLconnect.Close()
Catch ex As Exception
MsgBox(ex.Message)
'Return False
End Try
Return True
End Function
I know the database is at the location specified. On the SQLconnect.Open() part it errors out and tells me datasource cannot be empty. I opened the database using DB Browser and it is not corrupt. What am I doing wrong?
This is how I build my connection string for SQLite.
Dim constr As String = "Data Source=""" & FullFilePath & """;Pooling=true;FailIfMissing=false"
Think you are just missing the Double Quotes around the path.
Public Function ConnExist(strDB) As Boolean
Dim cs As String
Dim cnn As New SQLiteConnection
Dim cmd As New SQLiteCommand
cs = "Data Source=" & strDB & ";Version=3;New=False;"
If (IO.File.Exists(strDB)) Then
cnn = New SQLiteConnection(cs)
Try
cnn.Open()
cmd = cnn.CreateCommand()
cmd.CommandText = "SELECT * FROM tblSettings"
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
cnn.Dispose()
Catch ex As Exception
Return False
Exit Function
End Try
Else
Return False
Exit Function
End If
Return True
End Function

How do I assign the results of an SQL query to multiple variables in VB.NET?

This is my first attempt at writing a program that accesses a database from scratch, rather than simply modifying my company's existing programs. It's also my first time using VB.Net 2010, as our other programs are written in VB6 and VB.NET 2003. We're using SQL Server 2000 but should be upgrading to 2008 soon, if that's relevant.
I can successfully connect to the database and pull data via query and assign, for instance, the results to a combobox, such as here:
Private Sub PopulateCustomers()
Dim conn As New SqlConnection()
Dim SQLQuery As New SqlCommand
Dim daCustomers As New SqlDataAdapter
Dim dsCustomers As New DataSet
conn = GetConnect()
Try
SQLQuery = conn.CreateCommand
SQLQuery.CommandText = "SELECT Customer_Name, Customer_ID FROM Customer_Information ORDER BY Customer_Name"
daCustomers.SelectCommand = SQLQuery
daCustomers.Fill(dsCustomers, "Customer_Information")
With cboCustomer
.DataSource = dsCustomers.Tables("Customer_Information")
.DisplayMember = "Customer_Name"
.ValueMember = "Customer_ID"
.SelectedIndex = -1
End With
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
End Try
conn.Close()
End Sub
I also have no problem executing a query that pulls a single field and assigns it to a variable using ExecuteScalar. What I haven't managed to figure out how to do (and can't seem to hit upon the right combination of search terms to find it elsewhere) is how to execute a query that will return a single row and then set various fields within that row to individual variables.
In case it's relevant, here is the GetConnect function referenced in the above code:
Public Function GetConnect()
conn = New SqlConnection("Data Source=<SERVERNAME>;Initial Catalog=<DBNAME>;User Id=" & Username & ";Password=" & Password & ";")
Return conn
End Function
How do I execute a query so as to assign each field of the returned row to individual variables?
You probably want to take a look at the SqlDataReader:
Using con As SqlConnection = GetConnect()
con.Open()
Using cmd As New SqlCommand("Stored Procedure Name", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#param", SqlDbType.Int)
cmd.Parameters("#param").Value = id
' Use result to build up collection
Using dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection Or CommandBehavior.SingleResult Or CommandBehavior.SingleRow)
If (dr.Read()) Then
' dr then has indexed columns for each column returned for the row
End If
End Using
End Using
End Using
Like #Roland Shaw, I'd go down the datareader route but an other way.
would be to loop through
dsCustomers.Tables("Customer_Information").Rows
Don't forget to check to see if there are any rows in there.
Google VB.Net and DataRow for more info.