I have some doubts I would like to clear.
We have two features on our website we would like to provide to our customers for dealing with prescription drugs.
One feature allows potential new customers to transfer their prescription drugs from their current providing pharmacy to our pharmacy.
Another feature allows current customers to refill their current prescriptions.
Prescriptions must be either transferred from previous provider or must have existed before they can refilled.
To achieve the prescription transfer portion, I have two tables, one called Customer (which contains customer personal info as well as current providing pharmacy name and phone number) and the other called Prescriptions. This table contains prescription info. customerId is on this table as Foreign key to customer table.
The code below inserts records into customer table and prescriptions table for customers transferring their prescriptions from one pharmacy to our pharmacy.
I am also aware that I need to perform a check to see if customer trying to transfer prescriptiosn already exists on our table. I have not done this yet but will.
My doubt is how to handle the Refill portion of this task.
Any ideas is greatly appreciated.
Here is the code that inserts Transferred prescriptions.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim s As String
Dim sql As String
Dim connStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" & Server.MapPath("App_Data\GCP.accdb")
Try
SetRowData()
Dim table As DataTable = TryCast(ViewState("CurrentTable"), DataTable)
If table IsNot Nothing Then
s = "INSERT INTO Customer(FirstName, LastName, MiddleInitial, DOB, Email_Address, Phone, Address, City, State, ZipCode, PharmacyName, PharmacyPhone) Values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
sql = "Select Max(custId) From Customer"
'Response.Write(s)
'Response.End()
Dim con As New OleDbConnection(connStr)
Dim cmd1 As New OleDbCommand(s, con)
cmd1.Parameters.AddWithValue("", txtfName.Text)
cmd1.Parameters.AddWithValue("", txtMI.Text)
cmd1.Parameters.AddWithValue("", txtLName.Text)
cmd1.Parameters.AddWithValue("", txtDOB.Text)
cmd1.Parameters.AddWithValue("", txtemail.Text)
cmd1.Parameters.AddWithValue("", txtphone.Text)
cmd1.Parameters.AddWithValue("", txtAddress.Text)
cmd1.Parameters.AddWithValue("", txtcity.Text)
cmd1.Parameters.AddWithValue("", txtstate.Text)
cmd1.Parameters.AddWithValue("", txtzip.Text)
cmd1.Parameters.AddWithValue("", txtpharmacyName.Text)
cmd1.Parameters.AddWithValue("", txtPharmacyPhone.Text)
con.Open()
cmd1.ExecuteNonQuery()
cmd1.CommandText = sql
ID = cmd1.ExecuteScalar()
For Each row As DataRow In table.Rows
Dim txPrescription As String = TryCast(row.ItemArray(1), String)
If txPrescription IsNot Nothing Then
Try
s = "INSERT INTO Prescriptions(Prescription, custId) VALUES "
s += "('" & txPrescription & "', " & ID & ")"
'Response.Write(s)
'Response.End()
'Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(s, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Display some feedback to the user to let them know it was processed
lblResult.ForeColor = System.Drawing.Color.Green
lblResult.Text = "Your Prescriptions Transfer Request has been sent. Prescription requests are normally processed within 24 hours!"
'Clear the form
txPrescription = ""
txtfName.Text = ""
txtMI.Text = ""
txtLName.Text = ""
txtDOB.Text = ""
txtemail.Text = ""
txtphone.Text = ""
txtAddress.Text = ""
txtcity.Text = ""
txtstate.Text = ""
txtzip.Text = ""
Catch
'If the message failed at some point, let the user know
lblResult.ForeColor = System.Drawing.Color.Red
lblResult.Text = "Your record failed to save, please try again."
End Try
End If
Next
End If
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
Related
I am trying to check whether an email exists in my sql database from an an asp code behind
Basically a user will fill in a form and submit, I need to check wther that email exists first before inserting
Protected Sub btnSignup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSignup.Click
Response.Cookies("survey")("fullname") = TextBoxFullName.Text
Response.Cookies("survey")("surname") = TextBoxSurname.Text
Response.Cookies("survey")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("survey")("contactnumber") = TextBoxPhone.Text
Response.Cookies("survey")("email") = TextBoxEmail.Text
Response.Cookies("survey").Expires = DateTime.Now.AddDays(365)
'InsertCommand="INSERT INTO [Comp_20140409_Broadband] ([SignupName], [SignupGender], [SignupIDNo], [SignupEmailAddress], [CurrentProvider], [CurrentSpeed], [CurrentUsage]) VALUES (#SignupName, #SignupGender, #SignupIDNo, #SignupEmailAddress, #CurrentProvider, #CurrentSpeed, #CurrentUsage)"
If Not Page.IsValid Then Exit Sub
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql3 As String = "Select [PersonId] FROM [Users] WHERE [Email] = #Email"
Dim PersonId As Integer
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql3, myConnection)
myCommand.Parameters.AddWithValue("#Email", TextBoxEmail.Text)
PersonId = myCommand.ExecuteScalar()
myConnection.Close()
End Using
Dim updateSql2 As String = " INSERT INTO [Survey_Legal] ([LegalInsurance],[ThirdParty], [LegalIssues], [RequestLegal], [PersonId], [Category_Type]) VALUES (#LegalInsurance, #ThirdParty, #LegalIssues, #RequestLegal, #PersonId, #Type )"
Using myConnection2 As New SqlConnection(connectionString)
myConnection2.Open()
Dim myCommand2 As New SqlCommand(updateSql2, myConnection2)
myCommand2.Parameters.AddWithValue("#LegalInsurance", DDLLegal1.SelectedValue)
myCommand2.Parameters.AddWithValue("#ThirdParty", DDLLegal2.SelectedValue)
myCommand2.Parameters.AddWithValue("#LegalIssues", DDLLegal3.SelectedValue)
myCommand2.Parameters.AddWithValue("#RequestLegal", DDLLegal4.SelectedValue)
myCommand2.Parameters.AddWithValue("#PersonId", PersonId)
myCommand2.Parameters.AddWithValue("#Type", "Legal-Insurance")
myCommand2.ExecuteNonQuery()
myConnection2.Close()
End Using
This is how I do this. I check for a duplicate email address in my stored procedure with an output parameter.
CREATE Procedure sp_AddSubscriber
#Name as nvarchar(50),
#Email as nvarchar(50),
#AddSubscriber bit OUTPUT
AS
IF (SELECT COUNT(Email)
FROM TSubscribers
WHERE Email = #Email) = 0
BEGIN
INSERT TSubscribers (Name, Email)
VALUES (#Name, #Email)
SET #AddSubscriber = False
END
ELSE
SET #AddSubscriber = True
GO
I have been working on this particular issue for a couple of days, and scouring over SO, MSDN and other google searches has not proven to be of any use. I am trying to make a simple update to a SQL table. My SELECT and INSERT statements all work fine, but for some reason, this update will not work. I have set breakpoints and stepped through, and the code seems to be working fine -- the Catch ex as Exception is never reached after the .ExecuteNonQuery() fires off.
Could anyone give me an idea of why I've been unable to get a SQL update?
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim currentUser = Membership.GetUser(User.Identity.Name)
Dim username As String = currentUser.UserName
Dim userId As Guid = currentUser.ProviderUserKey
UserNameTextBox.Text = username
' Get Root Web Config Connection String so you don't have to encrypt it
Dim rootWebConfig As System.Configuration.Configuration
rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")
Dim connString As System.Configuration.ConnectionStringSettings
connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalSqlServer")
Dim conn As String = connString.ToString
Dim commandString As String = "UPDATE UserDetails SET FirstName ='" + FirstNameTextBox.Text + "' WHERE UserId ='" + userId.ToString + "'"
Dim fname As String = FirstNameTextBox.Text
Dim commandText As String = "UPDATE UserDetails SET FirstName=#firstname WHERE UserId=#UID;"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(commandText, connection)
command.CommandType = CommandType.Text
' Add UserId parameter for WHERE clause.
command.Parameters.Add("#UID", SqlDbType.UniqueIdentifier).Value = userId
' command.Parameters("#UID").Value = userId
' command.Parameters.AddWithValue("#UID", userId)
' Use AddWithValue to assign Demographics.
command.Parameters.Add("#firstname", SqlDbType.VarChar, 255).Value = fname
'command.Parameters.AddWithValue("#firstname", fname)
' command.Parameters("#firstname").Value = FirstNameTextBox.Text.ToString
Try
connection.Open()
command.ExecuteNonQuery()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
You're running "command.ExecuteNonQuery()" twice, meaning the second execution will likely return 0 rows affected since you already updated what you needed to update, and that's what you're assigning to rowsAffected. Are you sure the UPDATE isn't occurring?
Edit: Re your comment, did you check for IsPostBack when you LoadUser? If not, when you click SaveButton, you're going to reload the existing values, and then you'll be updating with those existing values.
I'm trying to display information on a piece of equipment the idea is that the user will type in an ID in the textbox and it will display the information on a grid view:
Dim ID As String = TxtSearch.Text
Dim cmd As SqlCommand
Dim ds As String = "Select * from Medical_Equipment where AssetID='" & ID & "''"
Dim strConnString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd = New SqlCommand(ds, con)
Try
con.Open()
GridView1.EmptyDataText = "No equipment with that Asset ID"
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
But it is not displaying the information Unclosed quotation mark after the character string '1001''.Incorrect syntax near '1001''
If AssetID is defined as numeric at database level the SQL statement should be:
"SELECT * FROM Medical_Equipment WHERE AssetID=" & ID
If it is defined as text then should be:
"SELECT * FROM Medical_Equipment WHERE AssetID='" & ID & "'"
I think you have a typo here:
Try this:
"Select * from Medical_Equipment where AssetID='" & ID & "'"
I have a button which when pressed, sets the user's rights in the db. (If Administrator UserTypeID is set to '2' and if Customer it is set to '1'). However when I run the below code, everything remains the same. I think it's from the SQL statement but I;m not sure. Can anyone help please?
Protected Sub btnSetUser_Click(sender As Object, e As System.EventArgs) _
Handles btnSetUser.Click
Dim conn As New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\...\WebSite3\db.mdb;")
Dim cmd As OleDbCommand = _
New OleDbCommand("UPDATE [User] SET [UserTypeID] WHERE Username=?", conn)
conn.Open()
cmd.Parameters.AddWithValue("#Username", txtUser.Text)
If ddUserType.SelectedItem.Text = "Administrator" Then
cmd.Parameters.AddWithValue("#UserTypeID", "2")
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to Administrator."
ElseIf ddUserType.SelectedItem.Text = "Customer" Then
cmd.Parameters.AddWithValue("#UserTypeID", "1")
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to Customer."
End If
conn.Close()
End Sub
End Class
If you add a parameter #Username your command should have such a parameter
SELECT [UserTypeID] FROM [User] WHERE Username = #Username
Also, you add an additional parameter later, which does not occur at all in your query! You call cmd.ExecuteNonQuery(), which works only for INSERT, UPDATE and DELETE queries.
Your query should probably look like this
UPDATE [User]
SET UserTypeID = #UserTypeID
WHERE Username = #Username
Dim cmd As OleDbCommand = New OleDbCommand( _
"UPDATE [User] SET UserTypeID = #UserTypeID WHERE Username = #Username", conn)
Dim userType As String = ddUserType.SelectedItem.Text
Dim userTypeId As Integer = If(userType = "Administrator", 2, 1)
cmd.Parameters.AddWithValue("#UserTypeID", userTypeId)
cmd.Parameters.AddWithValue("#Username", txtUser.Text)
conn.Open()
cmd.ExecuteNonQuery()
lblSetUser.Text = txtUser.Text + "was set to " & userType
UPDATE (some clarifications)
In "UDATE [User] SET UserTypeID = #UserTypeID WHERE Username = #Username"
[User] is the name of the table
UserTypeID is the name of the user type id column
#UserTypeID is the name of the user type id parameter (the new value)
Username is the name of the user name column
#Username is the name of the user name parameter
You might have to change these names in order to match your actual situation.
You are only performing a Select Query - which will not modify any data at all.
You will want to use an Update Query, supplying parameters for both the username and the user rights number.
You're doing a SELECT instead of an UPDATE...
New OleDbCommand("SELECT [UserTypeID] FROM [User] WHERE Username=?", conn)
should be
New OleDbCommand("UPDATE [User] SET [UserTypeID] = #UserTypeID WHERE Username = #Username", conn)
I have a form which goes to the following login script when it is submitted.
<%
Dim myConnection As System.Data.SqlClient.SqlConnection
Dim myCommand As System.Data.SqlClient.SqlCommand
Dim requestName As String
Dim requestPass As String
requestName = Request.Form("userName")
requestPass = Request.Form("userPass")
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username='" & requestName & "' AND password='" & requestPass & "'"
myConnection = New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
myCommand = New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myConnection.Open()
Dim reader As System.Data.SqlClient.SqlDataReader = myCommand.ExecuteReader()
%>
Now in theory, I should be able to get that Num_Of_User from the SQL Query and if it equals 1 than the login was successful. Is this the correct way? And how can I get the value that the SQL returns?
You are wide open to SQL injection using that code.
See happens if you enter the username as ' OR 2>1--
You need to change the to use a parametrized query.
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username=#username AND password=#password"
myConnection = New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
myCommand = New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myCommand.Parameters.AddWithValue("#username", requestName)
myCommand.Parameters.AddWithValue("#password", requestPass)
Also you are not handling any exceptions that might be thrown, nor disposing your objects.
Your code should look more like the following.
Dim numUsers as Integer
Using myConnection as New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username=#username AND password=#password"
Using myCommand as New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myConnection.Open
myCommand.Parameters.AddWithValue("#username", requestName)
myCommand.Parameters.AddWithValue("#password", requestPass)
numUsers = myCommand.ExecuteScalar()
End Using
End Using
The above code will make sure your objects are disposed, but won't handle any exceptions that might be thrown.
Try myCommand.ExecuteScalar(), which returns the value from the first column in the first row of the resultset - exactly the value you're after here.
Also, check into the ASP.Net 'built in' authentication methods - this might save you some effort.