ExecuteReader, Make field variable - sqldatareader

I want to make the Data Field a variable I wrote the code as follows. The SQL works but when I try to get the returned value it returns +StrVariable+ if I remove the + then it returns Strvariable literally.
Private Function FUNCTStrSN(StrVariable As String, StrSN As String) As String
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim r As SqlDataReader
Dim sqlstring As String
sqlstring = "Select " + StrVariable + " FROM HistorySNUnit WHERE SN='" + StrSN + "'"
sqlConn = New SqlConnection(DBConnection) : sqlConn.Open() : sqlComm = New SqlCommand(sqlstring, sqlConn) : r = sqlComm.ExecuteReader()
While r.Read()
Dim DBSN As String = CStr(r("StrVariable"))
StrSN = DBSN
End While : r.Close() : sqlConn.Close()
FUNCTStrSN = StrSN
End Function
How do I retrieve the value correctly? Thank you!

Try creating the SQL Command with parameters
Private Function FUNCTStrSN(StrVariable As String, StrSN As String) As String
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim r As SqlDataReader
Dim sqlstring As String
sqlstring = "Select #variable FROM HistorySNUnit WHERE SN=#value"
sqlConn = New SqlConnection(DBConnection) : sqlConn.Open() : sqlComm = New SqlCommand(sqlstring, sqlConn)
sqlComm.Parameters.AddWithValue("#variable", StrVariable)
sqlComm.Parameters.AddWithValue("#value", StrSN)
r = sqlComm.ExecuteReader()
While r.Read()
Dim DBSN As String = CStr(r(StrVariable))
StrSN = DBSN
End While : r.Close() : sqlConn.Close()
FUNCTStrSN = StrSN
End Function

Related

Stored Procedure fit in

How can I call a stored procedure in the following code instead if the sqlcommand statement,
<WebMethod> _
Public Function GetPtPrt() As String
Dim constr As String = ConfigurationManager.ConnectionStrings("ARTSQLConStrng").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT TblRegjoin.PrtFilenum, TblReg.Fname + ' ' + TblReg.Sname + ' ' + TblReg.Lname, PrtStatus FROM TblReg INNER JOIN TblRegjoin ON TblReg.Filenum = TblRegjoin.PrtFilenum WHERE (TblRegjoin.PtFilenum = 15090248) ORDER BY TblRegjoin.PrtFilenum")
cmd.Connection = con
Dim ds As New DataSet()
Using sda As New SqlDataAdapter(cmd)
sda.Fill(ds, "PtPrt")
End Using
Return ds.GetXml()
End Using
End Using
End Function
Try This:
<WebMethod> _
Public Function GetPtPrt() As String
Dim constr As String = ConfigurationManager.ConnectionStrings("ARTSQLConStrng").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("ProcedureName", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con
Dim ds As New DataSet()
Using sda As New SqlDataAdapter(cmd)
sda.Fill(ds, "PtPrt")
End Using
Return ds.GetXml()
End Using
End Using
End Function
Hope it helps.

What's wrong with my Count Query 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.

Web form to console application with timer

i have created a code in asp.net webform
now i want this code to be run in console application
but i don't know
how to invoke my timer
and where to place the code
can someone help me to convert
these code into a console application
Dim con1 As New SqlConnection(_start)
Dim sql12 As String = "SELECT Auction.AuctionID FROM Item INNER JOIN Auction ON Item.ItemID = Auction.ItemID Where Auction.Status='Valid' AND Auction.EndDate<=#endate "
Dim cmd12 As New SqlCommand(sql12, con1)
con1.Open()
cmd12.Parameters.AddWithValue("#endate", DateTime.Now)
Dim query As Integer = cmd12.ExecuteScalar
Dim sql123 As String = "UPDATE Auction SET Status ='Expired' WHERE AuctionID =#auction"
Dim cmd21 As New SqlCommand(sql123, con1)
cmd21.Parameters.AddWithValue("#auction", query)
cmd21.ExecuteNonQuery()
CalculateWinningPrice(query)
WinningBet()
timer1.Enabled = True
Public Sub CalculateWinningPrice(ByVal query As Integer)
Dim price As Integer
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (AuctionID = #auction)"
Dim cmd1 As New SqlCommand(sql1, con1)
cmd1.Parameters.AddWithValue("#auction", query)
Dim max As Double = Convert.ToDouble(cmd1.ExecuteScalar)
Dim cmd2 As New SqlCommand("SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (BiddingPrice <( SELECT MAX(BiddingPrice) AS Expr2 FROM BID AS BID_1 WHERE (AuctionID = #auction)))", con1)
cmd2.Parameters.AddWithValue("#auction", query)
Dim second As Double = Convert.ToDouble(cmd2.ExecuteScalar)
Dim cmd3 As New SqlCommand("SELECT BuyerID FROM BID WHERE(BiddingPrice =(SELECT MAX(BiddingPrice) AS Expr1 FROM BID AS BID_1 WHERE(AuctionID = #auction)))", con1)
cmd3.Parameters.AddWithValue("#auction", query)
Dim Buyer As Integer = Convert.ToInt32(cmd3.ExecuteScalar)
If max - second = 1 Then
price = second
Else
If max - second > 10 Then
price = second + 1
Else
If max - second > 100 Then
price = second + 10
Else
If max - second > 1000 Then
price = second + 1000
End If
End If
End If
End If
Dim cmd As New SqlCommand("INSERT INTO BID VALUES(#Date, #BiddingPrice,#Status,#AuctionID,#BuyerID,#WinningPrice)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#BiddingPrice", max)
cmd.Parameters.AddWithValue("#Status", "Won")
cmd.Parameters.AddWithValue("#AuctionID", query)
cmd.Parameters.AddWithValue("#BuyerID", Buyer)
cmd.Parameters.AddWithValue("#WinningPrice", price)
cmd.Connection = con1
cmd.ExecuteNonQuery()
End Using
End Sub
then calculate winning price
Private Sub WinningBet()
Dim Email As String
Dim auction1 As Integer = Convert.ToInt32(lblauction.Text)
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT TOP (1) Member.Email, BID.BidID FROM BID INNER JOIN Auction ON BID.AuctionID = Auction.AuctionID INNER JOIN Buyer ON BID.BuyerID = Buyer.BuyerID INNER JOIN Member ON Buyer.MemberID = Member.MemberID WHERE(Auction.AuctionID = #auction) and (BID.WinningPrice <>0) ORDER BY BID.BidID DESC"
Dim sqlcommand As New SqlCommand(sql1, con1)
sqlcommand.Parameters.AddWithValue("#auction", auction1)
Email = sqlcommand.ExecuteScalar()
End Using
Dim [to] As String = Email
Dim from As String = "virgoplaza11#gmail.com"
Dim password As String = ""
Dim subject As String = "BID"
Dim body As String = "Your bid has been Successfull Login to shoppingCart to Make Payment"
Dim email1 As New Thread(Sub() SendEmail1([to], from, password, subject, body))
email1.IsBackground = True
email1.Start()
End Sub
Private Sub SendEmail1(ByVal [to] As String, ByVal from As String, ByVal password As String, ByVal subject As String, ByVal body As String)
Using mm As New MailMessage(from, [to])
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential(from, password)
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
End Using
End Sub
To use the Forms timer:
Add a reference to System.Windows.Forms
Imports System.Windows.Forms
For the Web.UI timer:
Add references to System.Web and System.Web.Extensions
Imports System.Web.UI
At module level declare the new timer:
Dim timer1 As New Timer

ASP.NET/VB.NET/SQL Server 2012 - Page keeps loading

I'm trying to run this code, and whenever I press the 'Register' button, nothing is happening (the page is like loading but stays on the same page)
Code:
Public Sub register()
Dim Username As String = txtUsername.Text
Dim Surname As String = txtSurname.Text
Dim Password As String = txtPassword.Text
Dim Name As String = txtName.Text
Dim Address1 As String = txtAddress1.Text
Dim Address2 As String = txtAddress2.Text
Dim City As String = txtCity.Text
Dim Email As String = txtEmail.Text
Dim Country As String = drpCountry.Text
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.Text
Dim WorkLocation As String = txtWorkLocation.Text
Dim Age As Integer = Date.Today.Year - calDOB.SelectedDate.Year
Dim ProjectManager As String = "N/A"
Dim TeamLeader As String = "N/A"
Dim TeamLeaderID As Integer = "1"
Dim ProjectManagerID As Integer = "1"
Dim RegistrationDate As Date = DateTime.Today
Dim ContractType As String = "N/A"
Dim ContractDuration As Integer = 6
Dim Department As String = "N/A"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim registerSQL As SqlCommand
Dim sqlComm As String
Dim validateSQL As SqlCommand
Dim sqlValidate As String
sqlValidate = "SELECT * FROM users where username=" + txtUsername.Text.ToString
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
"City, Country, date_of_birth, age, Occupation, department, work_location, " +
"project_manager,team_leader, team_leader_id, project_manager_id, " +
"date_registration, contract_type, contract_duration) " +
"VALUES(#p1, #p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10,#p11,#p12,#p13,#p14,#p15," +
"#p16,#p17,#p18,#p19,#p20)"
conn.Open()
validateSQL = New SqlCommand(sqlValidate, conn)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
If dr.HasRows = False Then
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.CommandText = sqlValidate
Dim reader As SqlDataReader = validateSQL.ExecuteReader()
reader.Read()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
registerSQL.Parameters.AddWithValue("#p2", Password)
registerSQL.Parameters.AddWithValue("#p3", Name)
registerSQL.Parameters.AddWithValue("#p4", Surname)
registerSQL.Parameters.AddWithValue("#p5", Address1)
registerSQL.Parameters.AddWithValue("#p6", Address2)
registerSQL.Parameters.AddWithValue("#p7", City)
registerSQL.Parameters.AddWithValue("#p8", Country)
registerSQL.Parameters.AddWithValue("#p9", DOB)
registerSQL.Parameters.AddWithValue("#p10", Age)
registerSQL.Parameters.AddWithValue("#p11", Occupation)
registerSQL.Parameters.AddWithValue("#p12", Department)
registerSQL.Parameters.AddWithValue("#p13", WorkLocation)
registerSQL.Parameters.AddWithValue("#p14", ProjectManager)
registerSQL.Parameters.AddWithValue("#p15", TeamLeader)
registerSQL.Parameters.AddWithValue("#p16", TeamLeaderID)
registerSQL.Parameters.AddWithValue("#p17", ProjectManagerID)
registerSQL.Parameters.AddWithValue("#p18", RegistrationDate)
registerSQL.Parameters.AddWithValue("#p19", ContractType)
registerSQL.Parameters.AddWithValue("#p20", ContractDuration)
registerSQL.ExecuteNonQuery()
conn.Close()
ElseIf dr.HasRows = True Then
lblUsername.Text = "That Username (" + txtUsername.Text + ") is already registered/taken."
lblUsername.Visible = True
conn.Close()
End If
End Sub
Button event handler:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Is something wrong with the code?
From MSDN
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
It appears that you have the SqlDataReader open when you try to execute the insert command.
I will try to close it before using the insert command
If dr.HasRows = False Then
dr.Close()
' The following lines are probably a remainder of a copy/paste operation'
' They are not needed and you should remove them'
'validateSQL = New SqlCommand(sqlValidate, conn)'
'validateSQL.CommandText = sqlValidate'
'Dim reader As SqlDataReader = validateSQL.ExecuteReader()'
'reader.Read()'
' Now execute the insert command
Also your command to check for the user presence, apart from perfomance arguments, is wrong because introduces Sql Injection possibilities.
Summarizing try with these changes....
sqlValidate = "SELECT * FROM users where username=#uname"
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.Parameters.AddWithValue("#uname", txtUserName.Text)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
Dim userFound = dr.HasRows
dr.Close()
if userFound = False then
......

ASP.NET variable not getting assigned values

Im having problem with this asp.net code.
the variables qty and itname are not getting valid values ...can anyone find out the problem ?
Imports System.Data
Imports System.Data.SqlClient
Partial Class consolidate
Inherits System.Web.UI.Page
Public lastreq_no As Int32
Protected Sub btnconsolidate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnconsolidate.Click
Dim qtypen As Integer
Dim qtypencil As Integer
Dim qtygbag As Integer
Dim qtysugar As Integer
Dim i As Integer
Dim req As Integer
Dim qty As Integer
Dim itname As String = ""
Dim sqlcon As New SqlConnection("Data Source=user-hp\sqlexpress;initial catalog=campco;integrated security=true;")
If sqlcon.State = ConnectionState.Open Then
sqlcon.Close()
End If
sqlcon.Open()
Dim str As String
str = "Select Req_no from Requirements "
Dim cmd As New SqlCommand(str, sqlcon)
Dim sdr As SqlDataReader
sdr = cmd.ExecuteReader()
sdr.Read()
lastreq_no = sdr.GetInt32(sdr.VisibleFieldCount - 1)
For i = 0 To sdr.VisibleFieldCount - 1
req = sdr.GetInt32(i)
While req > lastreq_no
Dim selcomnd1 As String
Dim selcomnd2 As String
selcomnd1 = "Select #itname=It_name from Requirements where Req_no= #req"
selcomnd2 = "Select #qty= Quantity from Requirements where Req_no= #req"
Dim sqlcomnd1 As New SqlCommand(selcomnd1, sqlcon)
Dim sqlcomnd2 As New SqlCommand(selcomnd2, sqlcon)
sqlcomnd1.Parameters.AddWithValue("#itname", itname)
sqlcomnd2.Parameters.AddWithValue("#qty", qty)
sqlcomnd1.ExecuteScalar()
sqlcomnd2.ExecuteScalar()
TextBox1.Text = itname
TextBox2.Text = qty
sqlcon.Close()
sqlcon.Open()
Select Case (itname)
Case "Pen"
qtypen += qty
lastreq_no = req
Case "Pencil"
qtypencil += qty
lastreq_no = req
Case "Gunny bag"
qtygbag += qty
lastreq_no = req
Case "Sugar"
qtysugar += qty
lastreq_no = req
End Select
End While
Next
sqlcon.Close()
If sqlcon.State = ConnectionState.Open Then
sqlcon.Close()
End If
sqlcon.Open()
Dim comm As String
comm = "Insert into Consolidate (lastr_no,qtypen,qtypencil,qtygunnybag,qtysugar)values('" + lastreq_no.ToString + "','" + qtypen.ToString + "','" + qtypencil.ToString + "','" + qtygbag.ToString + "','" + qtysugar.ToString + "')"
Dim sqlcomm As New SqlCommand(comm, sqlcon)
Dim s As String
s = sqlcomm.ExecuteNonQuery()
sqlcon.Close()
End Sub
End Class
To start with, neither scalar statement is valid. Have you attempted to run those statements in SQL Management Studio or similar program to test the statements themselves? They should be something like:
selcomnd1 = "Select It_name from Requirements where Req_no=#req"
selcomnd2 = "Select Quantity from Requirements where Req_no=#req"
And then you would assign them in this manner:
itname = CType(sqlcmnd1.ExecuteScalar(), String) ' .ToString() would probably work here as well
qty = Convert.Int32(sqlcmnd2.ExecuteScalar())
Or you could use .TryParse for the qty:
Integer.TryParse(sqlcmnd2.ExecuteScalar(), qty)
The line
sqlcomnd1.Parameters.AddWithValue("#itname", itname)
provides an input parameter with the value itname. No value has been assigned to this variable.
You need to add an output parameter: see here for how to do this.
Get output parameter value in ADO.NET

Resources