getting the result of a sql statement in vs2010 vb.net - asp.net

I am doing a sql statement to get all the data that starts with "A" in the database.
Sub searchMap()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("WeddingPerfectionConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "SELECT LocationName FROM MapSearch WHERE LocationName=" Like ("1%")
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim customerId As Integer
If (reader.Read()) Then
customerId = reader.GetValue(0)
End If
reader.Close()
End Sub
And i would like to get the result and display it in a lable.
How can i go about doing it?

In SQL-Server:
Dim sql As String = "SELECT LocationID, LocationName FROM MapSearch WHERE LocationName LIKE 'A%'"
LIKE (Transact-SQL)

Related

ASP.NET Web API List All Records from SQL Server Table

I'm trying to follow a simple example (link below) to learn Web API and am unable to get it list all records from my underlying table. The following will only list the last record in the table when making the api call.
<HttpGet>
Public Function GetEmployees() As Employee
Dim reader As SqlDataReader = Nothing
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "myconnectionstring"
Dim sqlCmd As SqlCommand = New SqlCommand()
sqlCmd.CommandType = CommandType.Text
sqlCmd.CommandText = "Select * from tblEmployee"
sqlCmd.Connection = myConnection
myConnection.Open()
reader = sqlCmd.ExecuteReader()
Dim emp As Employee = Nothing
While reader.Read()
emp = New Employee()
emp.EmployeeId = Convert.ToInt32(reader.GetValue(0))
emp.Name = reader.GetValue(1).ToString()
emp.ManagerId = Convert.ToInt32(reader.GetValue(2))
End While
Return emp
myConnection.Close()
End Function
I've tried changing the function type to the following but get the error "Unable to cast object of type 'Employee' to type 'System.Collections.Generic.IEnumerable"
Public Function GetEmployees() As IEnumerable(Of Employee)
Credit to original tutorial:
http://www.c-sharpcorner.com/UploadFile/97fc7a/webapi-restful-operations-in-webapi-using-ado-net-objects-a/
In the code you provided, you're creating a single a variable "emp" of type "Employee". Your "While" loop executes and keeps resetting the "emp" variable on each iteration. Instead of using a single variable, you need a collection of Employees --
Public Function GetEmployees() As List(Of Employee)
Dim reader As SqlDataReader = Nothing
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "myconnectionstring"
Dim sqlCmd As SqlCommand = New SqlCommand()
sqlCmd.CommandType = CommandType.Text
sqlCmd.CommandText = "Select * from tblEmployee"
sqlCmd.Connection = myConnection
myConnection.Open()
reader = sqlCmd.ExecuteReader()
Dim empList As New List(Of Employee)()
While reader.Read()
Dim emp As Employee = New Employee()
emp.EmployeeId = Convert.ToInt32(reader.GetValue(0))
emp.Name = reader.GetValue(1).ToString()
emp.ManagerId = Convert.ToInt32(reader.GetValue(2))
empList.Add(emp)
End While
myConnection.Close()
Return empList
End Function
To sum up the changes --
Function should return a List of Employee instead of a single Employee object
Create a new Employee on every loop, populate it, then add it to the list
Close your connection before returning
Return the list

Not able to fetch data from sql database in asp.net web application using vb

I am using the below code to fetch data from SQL, I am not getting any error but code is not working on button click
Dim strSQL As String = String.Empty
strSQL = "SELECT * from jhg"
Using connection As New SqlConnection (ConfigurationManager.ConnectionStrings("xyz").ConnectionString)
Dim command As New SqlCommand(strSQL, connection)
connection.Open()
reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
GridView1.DataSource = reader
End While
'end connection and using close
I think you have to modify your code as follows,
Dim strSQL As String = String.Empty
strSQL = "SELECT * from jhg"
Using connection As New SqlConnection (ConfigurationManager.ConnectionStrings("xyz").ConnectionString)
Dim command As New SqlCommand(strSQL, connection)
connection.Open()
reader As SqlDataReader = command.ExecuteReader()
DataTable dt = new DataTable();
dt.Load(reader);
GridView1.DataSource = dt;
GridView1.DataBind();
You need to DataBind your GridView after providing the datasource:
GridView1.DataBind();

getting error when trying to execute an Sql command

DataReader throwing an error message when trying to execute an command in my vb.net page
And the code throwing error is:
Dim connectionString As String
Dim connection As SqlConnection
Dim sql As String
connectionString = \\\connection string\\\
connection = New SqlConnection(connectionString)
sql = "select * from jb_jobs where city='Los Angeles' "
connection.Open()
Dim reader As SqlDataReader = sql.ExecuteReader()
And the error is:
'ExecuteReader' is not a member of 'string'
How to resolve this???
Try adding this:
sql = "select * from jb_jobs where city='Los Angeles' ";
var sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Connection.Open();
var reader = sqlCommand.ExecuteReader();
Add this
connection.Open()
Dim cmd as new SqlCommand(sql,connection )
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim cmd As SqlCommand = new SqlCommand ();
cmd=(sql,connection);
cmd.CommandType=CommandType.Text;
Dim reader As SqlDataReader = cmd.ExecuteReader()

how to check existed username when signUp

I want to check if the username is already exist or not. this what I've reached but it's not working.
Dim cmdstr As String = "Select count(*) from Registration where username = '" & txtName.Text & "'"
Dim userExist As SqlCommand = New SqlCommand(cmdstr, con)
Dim temp As Integer = Convert.ToInt32(userExist.ExecuteScalar().ToString())
If (temp = 1) Then
Response.Write("user name is already Exist!!")
End If
Your open for SQL-Injection. Don't concatenate strings to a sql-query but use SqlParameters
You haven't opened the connection (i assume)
Here's a full sample:
Public Shared Function GetUserCount(userName As String) As Int32
Const sql = "SELECT COUNT(*) FROM Registration where username = #UserName"
Using con As New SqlConnection(connectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#UserName", userName)
con.Open()
Using reader = cmd.ExecuteReader()
If reader.HasRows
reader.Read()
Dim count As Int32 = reader.GetInt32(0)
Return count
End If
End Using
End Using
End Using
End Function
and use the method in this way:
Dim userCount As Int32 = GetUserCount(txtName.Text.Trim())
If userCount > 0
LblWarning.Text = "User-name already exists!"
End If

How to Use a parameter within SQL in Vb 2010 (web developer)

I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"

Resources