Storing multiple values from SQL Server statement - vb.net

Consider the following code
Dim cmd As New SqlCommand("SELECT * FROM [UserDetail].[User] where UserName = #username and UserPass = #password", con)
cmd.Parameters.AddWithValue("#username", login_username.Text)
cmd.Parameters.AddWithValue("#password", hash_pass)
Dim da As New SqlDataAdapter(cmd)
Suppose that there exist a column name status I want to store the result of status in a variable.
P.S I am a beginner with VB.NET so please bear with me

You can execute the statement on a SqlDataReader or fill DataTable. An example with SqlDataReader is
Dim reader As SqlDataReader
Dim cmd As New SqlCommand("SELECT * FROM [UserDetail].[User] where UserName =#username and UserPass=#password", con)
cmd.Parameters.AddWithValue("#username", login_username.Text)
cmd.Parameters.AddWithValue("#password", hash_pass)
reader = cmd.ExecuteReader()
Dim strStatus as String = ""
If reader.HasRows Then
reader.Read()
strStatus = reader.Item("status").ToString
End If
Here is the DataTable version
Dim cmd As New SqlCommand("SELECT * FROM [UserDetail].[User] where UserName =#username and UserPass=#password", con)
cmd.Parameters.AddWithValue("#username", login_username.Text)
cmd.Parameters.AddWithValue("#password", hash_pass)
Dim da As SqlDataAdapter = New SqlDataAdapter()
Dim dt As DataTable = New DataTable("TableA")
da.SelectCommand = cmd
da.Fill(dt)
Dim strStatus as String = ""
'you can process the DataTable in a for/for each loop or process a single row as follows
If dt.Rows.Count > 0 Then
strStatus = dt.Rows(0).Item("status").ToString()
End If

If status returns a single cell value(single row in status column) then you can use following method
Dim cmd As New SqlCommand("SELECT * FROM [UserDetail].[User] where UserName = #username and UserPass = #password", con)
cmd.Parameters.AddWithValue("#username", login_username.Text)
cmd.Parameters.AddWithValue("#password", hash_pass)
Dim status As String
status = IIf(IsDBNull(cmd.ExecuteScalar), "Not Available", cmd.ExecuteScalar)
'IsDBNull is used tocheck whether cmd.ExecuteScalar is null or what
'IIF() is used to handle null here, You can assign custom value for status variable if
'select returns null value
'If you dont need to use them its possible to write
' status = cmd.ExecuteScalar
See more about ExecuteScalar()

Related

How can I insert an image from SQL Server onto a button in VB.net?

I am having issues assigning an image to every button according to my database.
My current code:
Dim strsql As String
Dim ImgSQl As Image
Dim con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Image FROM Inventory WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSQl = myreader("Image")
con.Close()
btn1.Image = ImgSQl
This is the error I'm getting:
Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'
All I had to do was dim as Byte, also adding "()" is really important for it to work. Hope answering my own question helps a VB.net beginner out there.
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Image FROM Inventory WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
Dim ms As New MemoryStream(ImgSql)
btn1.Image = Image.FromStream(ms)
con.Close()
End Using

How do I get multiple values from query using OleDBConnection?

I have edited the previous code and tried this below, I have also changed the textbox into a listbox with the same name, but I now get no value in the listbox after running the below code:
myConnection.ConnectionString = providerEdit
Dim str As String
str = "SELECT [Email] FROM [PRD_Records] WHERE [ReceiveKMCWEMSAlerts] = Yes"
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
myConnection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
txtCreateAnnTo.Text = reader(0).ToString
End While
reader.Close()
End Using
Thanks everyone for your responses.... I found the problem with the code, it was very simple and I was just overlooking it. I update the coded below: myConnection.ConnectionString = providerEdit
Dim str As String
str = "SELECT [Email] FROM [PRD_Records] WHERE [ReceiveKMCWEMSAlerts] = Yes"
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
myConnection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
txtCreateAnnTo.Items.Add(reader(0).ToString)
End While
reader.Close()
End Using

Select from sql in vb and display in aspx page

Just wanna select a word from database and display in aspx page
Backend
Using da As New SqlDataAdapter
con.Open()
cmd.CommandText = "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';"
da.SelectCommand = cmd
Dim dt As New DataTable
da.Fill(dt)
Dim WordValue As String = dt.Rows(0).Item(0)
End Using
in aspx page
<%=WordValue%>
whats wrong here?
Assign Connection to the command object and also convert item(0) into string
Using da As New SqlDataAdapter
con.Open()
cmd.CommandText = "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';"
cmd.Connection =con
da.SelectCommand = cmd
Dim dt As New DataTable
da.Fill(dt)
Dim WordValue As String = Convert.ToString(dt.Rows(0).Item(0))
End Using
or
Using da As New SqlDataAdapter( "SELECT value_en as value FROM tbl_language WHERE element_id = 'a1';",con)
Dim dt As New DataTable
da.Fill(dt)
Dim WordValue As String = Convert.ToString(dt.Rows(0).Item(0))
End Using

DataSet update error requires InsertCommand

Trying to add a row to an Access 2010 database with VB 2013. Everything seems to work until the UPDATE statement when I get this error:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
My code is:
Dim sqlConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.OleDb.OleDbCommand()
Dim ds As New DataSet1()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "SELECT * FROM [extract] ;"
cmd.Connection = sqlConnection
sqlConnection.Open()
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
da.Fill(ds, "extract")
ds.Clear()
Dim newExtractRow As DataRow = ds.Tables("extract").NewRow()
newExtractRow("Field1") = "ABC123"
ds.Tables("Extract").Rows.Add(newExtractRow)
da.Update(ds, "Extract")
sqlConnection.Close()
Everything I've found so far seems to reference an SQL database, not OleDb connection.
You can probably use an OleDbCommandBuilder, like so
' your existing OleDbDataAdapter
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
' add the following lines:
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
For details, see
OleDbCommandBuilder Class
Working Example
For an Access table named extract with fields
ID - AutoNumber, Primary Key
Field1 - Text(255)
and data
ID Field1
-- -------
1 TEST999
the following VB.NET code will insert a second row into the table in the Access database
Using con As New OleDbConnection
con.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=C:\Users\Public\Database1.accdb;"
con.Open()
Using da As New OleDbDataAdapter("SELECT * FROM [extract]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Dim dt = New DataTable
da.Fill(dt)
Dim dr As DataRow = dt.NewRow
dr("Field1") = "ABC123"
dt.Rows.Add(dr)
da.Update(dt)
End Using
con.Close()
End Using
with the result
ID Field1
-- -------
1 TEST999
2 ABC123
The OleDbCommandBuilder object automatically (and invisibly) creates the INSERT, UPDATE, and DELETE commands based on the SELECT command that was supplied when the OleDbDataAdapter object was created.
You need to set the InsertCommand property
Dim da = New OleDb.OleDbDataAdapter(cmd.CommandText, sqlConnection)
da.InsertCommand = cmd
da.Fill(ds, "extract")
More info here

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