Setting MSSQL Entry as Variable in VB.NET
What I'm trying to do is select data out of a single cell in a MSSQL table using the SQL statement "SELECT JobData2 FROM tblJobs Where JobID=1" which will return a string and set that string as a variable within my VB.NET program the purpose of this is so that when all the MSSQL data is dumped and uploaded it will get uploaded in /home/variable/data/ on the FTP server anywhere heres the majority of the code any help would be much appreciated.
Public Sub Work()
'GLOBAL VARIABLES FOR DATABASE DUMP AND FTP UPLOAD
Dim dbserver As String = dbserverbox.Text
Dim dbusername As String = dbusernamebox.Text
Dim dbpassword As String = dbpasswordbox.Text
Dim dbpath As String = dbpathbox.Text
Dim ftpserver As String = ftpserverbox.Text
Dim ftpusername As String = ftpusernamebox.Text
Dim ftppassword As String = ftpusernamebox.Text
Dim ftpclientid As String = ftpclientidbox.Text
'CONNECTS TO MSSQL AND DUMPS ALL DATABASE DATA TO 'dbpath'
ToolStrip.Text = "Connecting to Database."
Dim conn As New SqlConnection()
conn.ConnectionString = "Data Source=" & dbserver & ";Initial Catalog=master;Persist Security Info=True;User ID=" & dbusername & ";Password= " & dbpassword & ";Connection TimeOut=60;"
If Directory.Exists(dbpath) Then
Thread.Sleep(1)
Else
Directory.CreateDirectory(dbpath)
End If
Do While working = 0
Try
conn.Open()
Catch ex As SqlException
MsgBox("Failed to Connect")
ToolStrip.Text = "Failed to Connect."
Thread.abort()
End Try
If conn.State = 1 Then
Dim time As Integer = 3000
dumpcount = dumpcount + 1
ToolStrip.Text = "Connected to Database. Dumping data. Dump Count = " & dumpcount
Try
Dim command As SqlCommand = New SqlCommand("EDRData.dbo.ExportAlldata", conn)
command.CommandTimeout = time
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@jobid", jobid)
command.Parameters.Add("@nonlogdata", "1")
command.Parameters.Add("@path", dbpath)
command.Parameters.Add("@user", dbusername)
command.Parameters.Add("@pwd", dbpassword)
command.Parameters.Add("@server", dbserver)
command.ExecuteNonQuery()
ToolStrip.Text = "Data Dump Completed."
Catch ex As SqlException
MsgBox(ex.Message)
End Try
Else
End If
conn.Close()
'END DATABASE DUMP CODE
'UPLOADS ALL DATA FILES IN 'dbpath' TO DATABASE SERVER
If Changer = 1 Then
ToolStrip.Text = "Connecting to FTP Server"
Dim ftp As FTPClient = Nothing
ftp = New FTPClient(ftpserver)
ftp.Login(ftpusername, ftppassword)
ftp.ConnectMode = FTPConnectMode.PASV
ftp.TransferType = FTPTransferType.ASCII
uploadcount = uploadcount + 1
ToolStrip.Text = "Uploading dumped data. Upload Count = " & uploadcount
Dim tbl() As String = {"tbldatastore.txt", "tblalarmlog.txt", "tblcomments.txt", "tbldatasources.txt", "tblfracreport.txt", "tblfracreportassemblyitems.txt", "tblfracreportcrew.txt", "tblfracreportfuel.txt", "tblfracreportquoteitems.txt", "tblfracreportrentals.txt", "tblfracstages.txt", "tbljobs.txt"}
Dim count As Integer = 0
Try
ftp.MkDir(ftpclientid)
Catch ex As Exception
End Try
For count = 0 To 11
ftp.Put(dbpath & "\" & tbl(count), ftpclientid & "\" & Changer & "-" & tbl(count))
Next
ftp.Quit()
Changer = 0
Else
ToolStrip.Text = "Connecting to FTP Server"
Dim ftp As FTPClient = Nothing
ftp = New FTPClient(ftpserver)
ftp.Login(ftpusername, ftppassword)
ftp.ConnectMode = FTPConnectMode.PASV
ftp.TransferType = FTPTransferType.ASCII
uploadcount = uploadcount + 1
ToolStrip.Text = "Uploading dumped data. Upload Count = " & uploadcount
Dim tbl() As String = {"tbldatastore.txt", "tblalarmlog.txt", "tblcomments.txt", "tbldatasources.txt", "tblfracreport.txt", "tblfracreportassemblyitems.txt", "tblfracreportcrew.txt", "tblfracreportfuel.txt", "tblfracreportquoteitems.txt", "tblfracreportrentals.txt", "tblfracstages.txt", "tbljobs.txt"}
Dim count As Integer = 0
Try
ftp.MkDir(ftpclientid)
Catch ex As Exception
End Try
For count = 0 To 11
ftp.Put(dbpath & "\" & tbl(count), ftpclientid & "\" & Changer & "-" & tbl(count))
Next
ftp.Quit()
Changer = 1
End If
ToolStrip.Text = "Connection pause, 1 minute."
Thread.sleep(60000)
'pauses the code for 1 minutes to make sure there will be no conflicts on the webpage
Loop
dumpcount = 0
uploadcount = 0
disconnect = 0
MsgBox("Connection aborted sucessfuly!")
ToolStrip.Text = "Connection aborted sucessfully!"
End Sub
I hate to post my own reply just to bump my thread but I really am in desperate need of some help, maybe if I explained a little better. I want to be able to add into my exsiting MSSQL code in the application above a way to pull a variable out of the same MSSQL database as my stored proceedures are located so basicly :Dim variable As String =
"SELECT JobData2 FROM tblJobs Where JobID=1"except instead of the variable simply being my MSSQL command it should be what that MSSQL command would return. In this case it would return "Imperial Oil" for me, if JobID=2 it would return "Shell Canada" etc and so on.I appreciate any help in advance, and agian sorry for replying to my own thread just to bump it.
hopefully I understand. Do you want to store the results returned back from SQL? if so, you may need to say, fill a dataset which holds the results returned, then you can access this. Or you can use a SqlDataReader to read data and store it in variables.
Please feel free to correct me - you wish to store the results returned from SQL after executing the query?
exactly I want to store the returned value from the query as a variable I've read a bit about SqlDataReader and it sounds like it would work I just don't know how to implement it within my code.
no worries, lets try to help you here :-)
you have 3 options, Let me run them down for your benefit and everyone else's
use a dataset to fill your data using a SqlDataAdapter - this is ideal for things where you are retrieving a reasonable number of records including schema information. It can be expensive and over kill for what you are after
use a SqlDataReader- a SqlDataReader as a fast forward only reader which only gets the values as it's reading row by row - pretty much what you want
use the ExecuteScaler method- this is probably what you want. When executed, it will return back the first row and the first column of data only and ignores the rest. This is probably what you want for your situation since it appears you only want the 1 column result correct?
so taking the last example as your probably most wanted solution:
'SQL
'SQL
'open connection
Dim theObjectResult as Object = theSQLCommand.ExecuteScaler()
'close connection
this will return back the result of the first column of the first row and ignores the rest.
You can now use this result in "theObjectResult" to wherever you want to, you can of course declare ths "theObjectResult" variable globally and use it.
does this help?
uhm sort of I understand what your doing but the data I'm looking for is not in the first column and first row. The first column is actually an automatically incrementing column, the second is a date/time column the third column displays legal land descriptions (LSD) for the jobs and the fourth column gives which company it is for, so for example
|JobId | JobDate | LSD | Company |
|-|
| 1 | 6/5/2006 | 676-76-76-576-54-W6M | Imperial Oil |
| 2 | 6/27/2006 | 999-91-12-345-67-W8M | Shell Canada |
|-|
So I wanna be able to to run a SQL query that will be able to retreive the company name based on the jobID which I've already figured out ( SELECT Company FROM tblJobs WHERE JobID=1 ). However where I am drawing a blank is how do I execute that query within VB.NET and set it's query return to a variable in VB.NET.
sorry the text ends up being formatted differently after its been posted than during the editing of the post but I do beleive you can still see how that database table is setup.
ok that's not a problem. We can use the SqlDataReader instead.
Dim theSqlDataReader as SqlDataReader = theSQLCommand.ExecuteReader(CommandBehavior.CloseConnection)
while theSqlDataReader.Read()
Dim theValue as Object = theSqlDataReader(ColumnNameOrIndex)
end while
so this command will execute a sql data reader and it will read each row of the results returned. For each row, you can go to the specific column and get the value you like, as I have shown
does this help?
ok heres how I understand it, the code below should return the results of my query to variable 'theValue', the only part I'm really confused on now is what I should be inputting for 'ColumnNameOrIndex'
Dim theSQLCommand as new SqlCommand ("SELECT Company FROM tblJobs WHERE JobID=1;")Dim theSqlDataReader as SqlDataReader = theSQLCommand.ExecuteReader(CommandBehavior.CloseConnection)
while theSqlDataReader.Read()
Dim theValue as Object = theSQLDataReader(ColumnNameOrIndex)
end while
ColumnNameOrIndex should be placed with either the columnName you want to retrieve the data from or the index
However to me, from your SQL Query, you are only selecting 1 column, Company, and would return only 1 record as JobID should = 1.
so you are returning 1 record, assuming JobID is a unique ID field, and 1 column, company. If this is the case, you are better to use the ExecuteScaler() method as mentioned earlier.
if you want to select all records:
SELECT * FROM tblJobs WHERE JobID = 1
however I believe this is not what you like but only want the Company field to return with the result correct?
going back to the SqlDataReader, when reading each row, you can specify what column to get the value from, by either giving it the columnName to read, or the columnIndex, ColumnName would be ideal as you would know the columnName to retrieve the data from.
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=769501&SiteID=1
ok so
Dim theSqlDataReader as SqlDataReader = theSQLCommand.ExecuteReader(CommandBehavior.CloseConnection)
while theSqlDataReader.Read()
Dim theValue as Object = theSqlDataReader(Company)
end while
Would work however how do I tell it which row to select from, in some situations I would want the company name out of row 1 other situations I would want the company name out of row lets say for example 5.
well you would just keep looping and keeping a counter to indicate what row you are on. The While theSqlDataReader.Read() loops through EACH row until no more rows...so you may wish to keep a counter and see what row you are on:
Dim theCurrentRow as Integer = 0
Dim theSqlDataReader as SqlDataReader = theSQLCommand.ExecuteReader(CommandBehavior.CloseConnection)while theSqlDataReader.Read()
if theCurrentRow = 5 then
Dim theValue as Object = theSqlDataReader(Company)
end if
theCurrentRow = theCurrentRow + 1end while
perfect I think that will work let me play with that for a bit
oh and thank you very much for the help I do appreciate it
no worries, im glad I could help ;-)
hmm well doesn't seem to work heres my test code
Imports System.Data.SqlClient
Public Class Form1
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim variable As String = TextBox1.Text
Dim conn As New SqlConnection()
conn.ConnectionString = "Data Source=welldaq\DBINFO;Initial Catalog=EDRData;Persist Security Info=True;User ID=sa;Password=*****;Connection TimeOut=60;"
Dim theCurrentRow As Integer = 0
conn.Open()
Dim theSqlDataReader As SqlDataReader = theSQLCommand.ExecuteReader(CommandBehavior.CloseConnection)
While theSqlDataReader.Read()
If theCurrentRow = variable Then
Dim theValue As Object = theSqlDataReader("Company")
MsgBox(theValue)
End If
theCurrentRow = theCurrentRow + 1
End While
conn.Close()
End Sub
End Class