How to display query results from SQL server in VB? - sql-server

I am trying to display query results from SQL server in VB. I wrote following code, but not getting how to "Just display the results";
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
Return reader
End Function
Can any one guide? Thank you

I corrected a few things and now your function works fine for me:
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Dim reader As SqlDataReader
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username, WindowsLogin FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query '
reader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
'NOTE: (^^) You are trying to read 2 columns here, but you only '
' SELECT-ed one (username) originally... '
' , Also, you can call the columns by name(string), not just by number '
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
'Return reader { note: reader is not valid after it is closed } '
Return "done"
End Function
Let me know if you have any questions.

Related

VB.NET SQL conversion error when trying to read data

I'm trying to get data from a database but keep getting the following error.
Conversion failed when converting the varchar '102A' to data type int
The database table has 3 columns UserID, UserName, UserInfo, all of them defined as type varchar.
There is also a user in the table with ID 102A.
I'm trying to get the Username of the User with ID 10307.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim datareader As SqlDataReader
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True"
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM Users WHERE UserID = 10307"
datareader = cmd.ExecuteReader
datareader.Read()
MsgBox(datareader.GetValue(2))
datareader.Close()
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I also tried to change datareader.GetValue to datareader.GetString but I get the same error.
Can anyone help me please, I've been stuck for days now...
Thank you

Deadlock issue in SQL Server using VB.Net

I have developed an application which runs with multiple instance simultaneously. In the application it connects to a SQL Server and fetches some data, while working on that data, it updates the row as picked so that no other instance of the application picks up the same record for research. While updating the row for the fetched record, sometime it gets deadlock issue and not updating the record as already picked.
Dim MyConnection As SqlConnection
Try
MyConnection = New SqlConnection(connString)
MyConnection.Open()
Dim tableName As String = myTableName
Dim sqlQuery As String = "Select Top 1 * from " + tableName + " where "<some condition>
Dim MyCommand As SqlDataAdapter = New SqlDataAdapter(sqlQuery, MyConnection)
Dim DS as DataSet = New DataSet
MyCommand.Fill(DS, tableName)
If DS.Tables(0).Rows.Count >= 1 Then
sqlQuery = "UPDATE " + tableName + " SET Fld = #fld where Cond1= '" + DS.Tables(0).Rows(0).Item("Cond1").ToString + "'"
Dim cmd As New Data.SqlClient.SqlCommand(sqlQuery)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#fld", Data.SqlDbType.VarChar).Value = "Picked"
Try
cmd.Connection = MyConnection
cmd.ExecuteNonQuery() <---- Dead lock occurs here
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
Catch ex As Exception
MsgBox(ex.ToString)
Finally
MyConnection.Close()
End Try
While executing the update statement, deadlock occurs and it goes to catch block and then exits the sub without updating the required field in the table. I want it to try to update until the dead lock is removed.
Creating Stored Procedure is not possible as I do not have the admin rights to this DB.
How can I overcome the problem?

Cannot insert records into a SQL Server CE database

I cannot insert records into a SQL Server CE database. I have read lots of articles but I still did not receive a proper answer for that.
This is my code. Database is located in the bin folder of the project.
Dim strConnection As String
strConnection = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\Barcode_UAT.sdf;Persist Security Info=False"
Dim cn As New SqlCeConnection(strConnection)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
Dim cmd As SqlCeCommand
Dim sql As String = "insert into [tbl_Barcodes] ([SerialNo],[ItemId],[Date]) values (#SerialNo,#ItemId,#Date)"
Try
cmd = New SqlCeCommand(sql, cn)
cmd.Parameters.AddWithValue("#SerialNo", "12121333")
cmd.Parameters.AddWithValue("#ItemId", "Item01010")
cmd.Parameters.AddWithValue("#Date", "2012-2-2")
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch sqlexception As SqlCeException
MessageBox.Show(sqlexception.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cn.Close()
End Try
It seems like you are missing the bin folder in your Data Source location path

How to get rid of this error: An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'

The purpose of my application is when a user types in a customer, their username and a message into the respective textboxes, it's supposed to be recorded into a table on SQL Server after the user presses the send button.
Here's my code:
Public Class Form1
Dim Con As OleDbConnection
Dim cmd As New OleDbCommand
Dim conString As String = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
Public Sub MessageSent()
Try
Dim con As New OleDbConnection
con.ConnectionString = conString
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Message Sent")
con.Close()
con.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
MessageSent()
End Sub
I'm getting the following error:
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.
What is it that I'm doing wrong and how can this be resolved.
It looks like you are trying to give a SQL Server connection string to an OleDbConnection. You need to either use a SqlConnection to open with that connection string or else you need to create a valid OLEDB connection string to point to that database. For reference, see this site.
When you want to connect to an MS SQL database you should use SQL connection instead of OleDbConnection.
The same is true for sqlCommand over the OldDbommand.
This SO question as some answers explaining the difference between Sql and OldDb Client.
Public Sub MessageSent()
Try
Using con As SqlConnection = New SqlConnection
con.ConnectionString = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
con.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I think you are just missing this bit: Provider=SQLOLEDB;
For example:
Dim conString As String = "Provider=SQLOLEDB;Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"

Displaying Data from SQL to vb.net textbox

I'm trying to retrieve data from sql server to vb.net textbox but i don't know what else to do all the tutorials i have are just to retrieve records from the database to datagrid view..please help..
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Students WHERE RFID like '%" & txtrfid.Text & "%'"
End With
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
cn.Close()
txtname.Text = 'Firstname'
You're populating a DataTable with the data from the database so you then have to get the data from that DataTable into the TextBox. You can do that with data binding, which is how you've probably seen it done with a grid, e.g.
txtname.DataBindings.Add("Text", dt, "Firstname")
That's definitely how you'd do it if you were retrieving multiple records that you wanted to be able to navigate, although you'd probably use a BindingSource in between. If there's only one record then you might instead just move the data manually, e.g.
txtname.Text = CStr(dt.Rows(0)("Firstname"))
If you want to display only a single value (FirstName) from Table then see following piece of code
Using conn As New SqlConnection("connstr")
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstname FROM Students WHERE RFID ='" & txtrfid.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
Textbox1.Text = ""
Textbox1.Text = txtName
else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
There are many ways to retrieve the data. You can simply retrieve the data from sql database to textbox using sql data reader which is one of my favourite. Let me share to you.
Note : Don't forget to import system.data.sqlclient
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
strConn = "Data Source=" & servernamehere & ";Initial Catalog=" & databasenamehere & ";User ID=" & userid & ";Password=" & password
sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("Your query here", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
txtrfid.Text = myreader.Item("column name from sql database table").Tostring
End If
sqlConn.Close()
End Sub
You may catch the exception with Try-Catch Technique.

Resources