What's wrong with my Count Query asp.net - asp.net

Public state_name as String
state_name = Textbox1.Text
Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=" & state_name
Using conn As New SqlConnection(constr)
Using comm As New SqlCommand()
conn.Open()
With comm
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
Label1.Text = count
End Using
End Using
The code shows an error
Invalid column name 'California'.
But California is already present in my State table, I want to count all the cities comes under state_name= california which I have entered in my State table.
I want the output as
California (3)

You want to use Parameterized Query to avoid SQL Injection.
Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=#State_Name"
Using conn As New SqlConnection(constr)
Using comm As New SqlCommand()
conn.Open()
With comm
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#State_Name", state_name)
End With
Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
Label1.Text = count
End Using
End Using

Because you didn't surround your variable with quotes. "state_name = '" + state_name + "'"
But, you should use a parameter instead.

Related

Query string not retrieving data values

Hope you guys could give me some help.
I have a asp.net web form which gets data from SQL database and displays it on webpage via product code number or product description.
Searching by description will display a list of similar products where each list will have a button with the product code when clicked will open another site with extra product information,
e.g.
13892
14589
17485
00010
08890
The problem is all the codes that start from 1 upwards will show more details, but when I click on product codes that start with 0 such as 00010, 08890 will show no data when in fact there should be data.
Any help would be appreciated.
code I have below,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Val(Request.QueryString("Stock_code")) <> 0 Then
Dim dt As DataTable = New DataTable
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & _
"AND LOC_STOCK_CODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & Val(Request.QueryString("stock_code")) & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & Val(Request.QueryString("stock_code")) & "'"
Using cmd4 As SqlCommand = New SqlCommand(strQuery4)
Dim da3 As SqlDataAdapter = New SqlDataAdapter
Dim dt4 As New DataTable
cmd4.Connection = cnn : cnn.Open()
da3.SelectCommand = cmd4
da3.Fill(dt4)
For i = 0 To dt4.Rows.Count - 1
Label8.Text = dt4.Rows(i).Item("Retail_Rest_Split")
Next
End Using
cnn.Close()
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = cnn : cnn.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
For i = 0 To dt.Rows.Count - 1
Label7.Text = dt.Rows(i).Item("Stock_Code")
Label1.Text = dt.Rows(i).Item("Notes")
Label3.Text = dt.Rows(i).Item("Retail_Price")
Label4.Text = dt.Rows(i).Item("Pack_Size")
Label5.Text = dt.Rows(i).Item("Stock_Description")
'Label8.Text = dt.Rows(i).Item("Pack_Size")
Label9.Text = dt.Rows(i).Item("Net_Weight")
Label10.Text = dt.Rows(i).Item("Gross_Weight")
GridView1.DataSource = dt
GridView1.DataBind()
Next
End Using
cnn.Close()
Dim dt3 As DataTable = New DataTable
Using cmd3 As SqlCommand = New SqlCommand(strQuery3)
Dim da2 As SqlDataAdapter = New SqlDataAdapter
cmd3.Connection = cnn : cnn.Open()
da2.SelectCommand = cmd3
da2.Fill(dt3)
End Using
For i = 0 To dt3.Rows.Count - 1
Label6.Text = dt3.Rows(i).Item("Chinese_Description")
Next
Dim cmd2 As New SqlCommand
Dim dt2 As New DataTable
Dim da As New SqlDataAdapter
With cmd2
.Connection = cnn
.CommandText = strQUery2
End With
da.SelectCommand = cmd2
da.Fill(dt2)
GridView1.DataSource = dt2
GridView1.DataBind()
End If
End Sub
You want to use a paramaterized query like this (I'm going to fold that query string to make it more readable without having to scroll horizontally):
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description],
STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as
[Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as
[Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM
dbo.STK_STOCK WHERE STKCODE = #StockCode"
Using cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#StockCode", Request.QueryString("Stock_code"))
' Do your other stuff here.
End Using
Note, that you don't want to just use string concatenation to insert your query parameter. That opens you up to SQL injection attacks.
Instead, you use a placeholder in your query like #StockCode. Then you call AddWithValue on the command to give it the value of that parameter.
You can also explicitly specify the parameter type if you need to:
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
Assuming they are all 5 digit codes, this will make sure the stock code is numeric.
Replace
Val(Request.QueryString("Stock_code"))
with
String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Will raise an exception if Request.QueryString("Stock_code") is not parsed as integer, which prevents against malicious injection.
For example:
Dim stockCode = String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & stockCode & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & "AND LOC_STOCK_CODE = '" & stockCode & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & stockCode & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & stockCode & "'"
#dwilliss has just answered the question using parameters, which is probably better than my method. Posting this anyway

vb.net OleDbDataAdapter not working with Select From Where

If I Debug this I just get a Invalid Columnname Error("Name of the Object"). I am using a SQL database.
Protected Sub ddlKunden_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlKunden.SelectedIndexChanged
Dim strSql As String
Dim kontakt As String = ddlKunden.SelectedItem.Value
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.ConnectionString = strConnection
connection.Open()
'Kontaktpersonen laden
strSql = "SELECT * FROM Kontaktpersonen WHERE Nr =" & Chr(34) & kontakt & Chr(34)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbP)
End Using
ddlKontaktperson.Items.Clear()
ddlKontaktperson.DataSource = dtbP
ddlKontaktperson.DataTextField = "AP_Nam"
ddlKontaktperson.DataValueField = "ID"
ddlKontaktperson.DataBind()
End Using
ddlKontaktperson.Visible = True
End Sub
The Error pops at
dad.fill(dtbP)
It should select all rows Where Nr="SELECTED VALUE" and you select it in a dropdownlist. And all these rows should be saved in a Datatable then and are used in another dropdownlist.
It works when I try the exact same thing without the where.
Example:
'Kunden laden
strSql = "SELECT * FROM Kontakte"
dtbK = New DataTable()
Using dad As New OleDbDataAdapter(strSql, connection)
dad.Fill(dtbK)
End Using
ddlKunden.Items.Clear()
ddlKunden.DataSource = dtbK
ddlKunden.DataTextField = "Nr"
ddlKunden.DataValueField = "Nr"
ddlKunden.DataBind()
Please try following code
You do not need to use "'" around parameters
Just add these values as a parameter to the oledbcommand with its value and type
Otherwise, your sql command will be vulnerable to sql injection
Dim strConnection As String = "Provider=sqloledb;Data Source=(local);" &
"Initial Catalog=kodyaz;" &
"User Id=sa;Password=sa"
Dim kontakt As Int32 = 1
Dim dtbP As DataTable
Using connection As OleDbConnection = New OleDbConnection(strConnection)
connection.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = connection
cmd.CommandText = "SELECT * FROM Kontaktpersonen WHERE Nr = ?"
cmd.Parameters.AddWithValue("Nr", kontakt)
dtbP = New DataTable()
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtbP)
End Using
End Using

Trouble getting date value

I am modifying a webpage. Webpage is using visual basic and my database is a SQL database.
The webpage gives me the total Sick, Comp, and Vacation time off. Right now, I get the logon name of whoever's logged onto the computer, and I look up the EmployeeID in a tblEmployees so I can search tblTimeAvailable by the EmployeeID, and then add up the different times.
I want to also get the StartDate from tblEmployees so I can also search by anniversary date (after I calculate it from the Start Date). I'm getting an error "Value of type 'Integer' cannot be converted to 'Date' on the rvsd=command2.ExecuteNonQuery line. Here's my code:
Dim rve As Object
Dim rvsd As Date
Dim dt As Date = Today
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim sqlstdt As String = "SELECT StartDate FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
Dim command2 As New SqlCommand(sqlstdt, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
command2.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
rve = command.ExecuteScalar
rvsd = command2.ExecuteNonQuery
End Using
Dim theDateThisYear As Date
theDateThisYear = DateSerial(Year(Now), Month(rvsd), Day(rvsd))
If theDateThisYear < Now() Then
theDateThisYear = DateAdd("yyyy", 1, theDateThisYear)
End If
Dim NextAnniversary As Date = theDateThisYear
MsgBox(NextAnniversary)
'Get Sick Time - DOES NOT INCLUDE CHECKING TO MAKE SURE LESS THAN ANNIV DATE YET
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #emp"
Dim command As New SqlCommand(sqls1, con)
con.Open()
command.Parameters.Add(New SqlParameter With {.ParameterName = "#emp", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
rvsa = command.ExecuteScalar
End Using
Thanks in advance for any help you can give me!
Assuming that the column [StartDate] in the database has a type of DateTime then all you need to do is
rvsd = CDate(command2.ExecuteScalar)
Although you could have retrieved both values with one query:
SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
and so
Dim rve As String
Dim rvsd As Date
Dim connStr As String = "Data Source=WillSQL\ict2;Initial Catalog=timesql_testing;Integrated Security=SSPI"
Dim sql = "SELECT [EmployeeID], [StartDate] FROM [tblEmployees] where [login] = #loginname"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(Sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
rve = rdr.GetString(0)
rvsd = rdr.GetDateTime(1)
End If
End Using
End Using

Want DropDownlist value to get stored by ID

I am working on asp.net using VB and SQL database
I have two tables mst_Emp & mst_dept
mst_dept got following columns (dpt_ID(PK),dpt_name,dpt_descrip)
mst_Emp got following columns (Emp_ID,Emp_FirstName,Emp_LastName,Emp_Address,Emp_ContactNo,Dept_ID(Foreign key),Marital_Status,Gender)
Now I have a Employee Detail Form in that I have Department Name label(DataBind from mst_Dept) and I have DropDownList for that to select. If some choose value from DropDownList I want it to get stored by Dept_ID in database. How can I do that ?
Try binding your Department Dropdownlist like
Using sqlconn As New SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString)
If sqlconn.State = ConnectionState.Closed Then
sqlconn.Open()
End If
Dim ds As New DataSet()
Dim qry As String = "Select dpt_ID,dpt_name from mst_Dept"
Using cmd As New SqlCommand(qry, sqlconn)
Dim sda As New SqlDataAdapter(cmd)
sda.Fill(ds)
D_ddlDepartment.DataSource = ds
D_ddlDepartment.DataValueField = "dpt_ID"
D_ddlDepartment.DataTextField = "dpt_name"
D_ddlDepartment.DataBind()
D_ddlDepartment.Items.Insert(0, "-- Select Department --")
If sqlconn.State = ConnectionState.Open Then
sqlconn.Close()
End If
End Using
End Using
and you can access the Dept_id like
Dim Deptid As Integer = Convert.ToInt32(D_ddlDepartment.SelectedValue)
FINALLY GOT IT THANKS :-)
Dim ds As New DataSet
Dim cmd1 As SqlCommand = New SqlCommand()
Dim sqlconn As SqlConnection = New SqlConnection()
sqlconn.ConnectionString = "Data Source=PRGM\SQLEXPRESS;Initial Catalog=HRMS;Integrated Security=True"
sqlconn.Open()
cmd1 = New SqlCommand("select Dpt_ID,Dpt_Name from mst_Dept", sqlconn)
'Dim qry As String = "select Dpt_ID,Dpt_Name from mst_Dept"
'cmd1 As New SqlCommand(qry, sqlconn)
Dim sda As New SqlDataAdapter(cmd1)
sda.Fill(ds)
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataValueField = ds.Tables(0).Columns("Dpt_ID").ColumnName
DropDownList1.DataTextField = ds.Tables(0).Columns("Dpt_Name").ColumnName
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, "-- Select Department --")
sqlconn.Close()
End If

Invalid attempt to read when no data is present error

I have a function whose sole purpose is to fetch some data when a button is pressed and it's called multiple times. This is the function code:
Function GetData2(ByVal clientNo As Integer) As List(Of SocioInfo)
Dim theResults2 = New List(Of SocioInfo)
Dim connStr = "Data Source=localhost;Initial Catalog=testdb;Integrated Security=True;MultipleActiveResultSets=true"
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [FirstName], [LastName] FROM [CustInfo] Where ([NumCuenta] = #SocioNum)"
Dim sql2 = "SELECT [AcctName], [AcctNum], [NewAcct], [Balance] From [ACCT_NEW] Where ([AcctNum] = #SocioNum)"
Dim sqlCmd = New SqlCommand(sql, conn)
Dim sqlCmd2 = New SqlCommand(sql2, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
sqlCmd2.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
Dim rdr2 = sqlCmd2.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
})
End While
While rdr2.Read
theResults2.Add(New SocioInfo With {
.CuentaName = rdr.GetString(0),
.AcctNum = rdr.GetValue(1),
.AcctFull = rdr2.GetValue(2),
.Balance = rdr2.GetValue(3)
})
End While
End Using
Return theResults2
End Function
I am not 100% sure if this is the best way to do this (basically need to get data from two different tables). Thing is, while Rdr shows me no error, Rdr2 just blows in the face. The exception is this:
Invalid attempt to read when no data is present.
In the second loop you are trying to use the first SqlDataReader but this is not possible because the first loop has already reached the end of the input data.
If you need joined data between the two tables a better approach is to use just one query using the JOIN operator. This query works assuming that each customer in the CustInfo table has one account in the ACCT_NEW table
Dim sql = "SELECT c.FirstName, c.LastName, a.AcctName, a.AcctNum, a.NewAcct, a.Balance " & _
"FROM CustInfo c INNER JOIN ACCT_NEW a ON a.AcctNum = c.NumCuenta " & _
"WHERE NumCuenta = #SocioNum "
Using conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("#SocioNum", CDbl(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
While rdr.Read
theResults2.Add(New SocioInfo
With {
.Nombre = rdr.GetString(0),
.LastName = rdr.GetString(1)
.CuentaName = rdr.GetString(2),
.AcctNum = rdr.GetValue(3),
.AcctFull = rdr.GetValue(4),
.Balance = rdr.GetValue(5)
})
End While
End Using

Resources