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
Related
I created a stored procedure to include a new user for my system. Parameters are: Name, Mail and Password (all varchar). The stored procedure first checks if the mail is already in the database. If not, then the information in added to the table. At the end, the output is a table with the user data.
CREATE PROCEDURE [dbo].[user_new]
(#name VARCHAR(50),
#mail VARCHAR(50),
#password VARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #exist INT
SELECT #exist = COUNT([id])
FROM [dbo].[User]
WHERE [mail] = #mail
IF #exist = 0
INSERT INTO [dbo].[User] ([name], [mail], [password])
VALUES (#name, #mail, #password)
SELECT
#exist AS [exist], [id], [name], [mail]
FROM
[dbo].[User]
WHERE
[mail] = #mail
END
GO
When I execute the stored procedure in SSMS, everything works fine: when I insert a new mail, field [exist] returns 0. When I insert a mail that already exist, field [exist] returns 1. So far, so good.
When I execute the stored procedure from my .NET application (which has a lot of other calls that are working fine), the error happen: no matter if I try to add a new or an existing mail, [exist] always returns 1. I tried to change the logic several times, but I always get the wrong result.
Here is the .NET code:
Public Function api_v2_player_new(<FromBody> s As User) As Object
Dim arrParameters(,) As String = {{"#name", s.Name}, {"#mail", s.Mail}, {"#password", s.Password}}
Dim dtc As Data.DataTableCollection = SQL.Execute("dbo.user_new", arrParameters)
Return SQL.toJson(dtc(0))
End Function
Public Class SQL
Public Shared Function runStoredProcedure(ByVal cmd As SqlCommand) As Data.DataTableCollection
Dim spName As String = cmd.CommandText.ToString
cmd.CommandTimeout = 120
Dim cs As String = System.Configuration.ConfigurationManager.ConnectionStrings("csKickerliga").ConnectionString
Dim connection As SqlConnection = Nothing
connection = New SqlConnection(cs)
Dim dt As DataTable = New DataTable()
cmd.Connection = connection
connection.Open()
Dim adp As New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Return ds.Tables
connection.Close()
End Function
Shared Function Execute(spName As String, arrParameters(,) As String) As Data.DataTableCollection
Dim cmd As SqlCommand = New SqlCommand(spName)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
For i = 0 To (arrParameters.Length / 2) - 1
.AddWithValue(arrParameters(i, 0), arrParameters(i, 1))
Next
End With
Dim dtc = runStoredProcedure(cmd)
Return dtc
End Function
Shared Function toJson(dt As DataTable) As List(Of Object)
Dim oList As New List(Of Object)
Dim o As New Dictionary(Of String, Object)
Dim data As Object
For Each r As DataRow In dt.Rows
o = New Dictionary(Of String, Object)
For Each c As DataColumn In dt.Columns
If IsNumeric(r(c.ColumnName)) Then
If Not r(c.ColumnName).ToString.Contains(".") Then
data = CInt(r(c.ColumnName))
Else
data = r(c.ColumnName).ToString
End If
Else
data = r(c.ColumnName).ToString
End If
o.Add(c.ColumnName, data)
Next
oList.Add(o)
Next
Return oList
End Function
End Class
Found the issue. The code was executing the stored procedure twice:
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Therefore on the recond run the record already existed because it was created on the first run. I removed one of the lines and now it's working!
I'm having problems with this block of code, the error is: String or binary data would be truncated
Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
Using cnnentry As New SqlConnection("Data Source=NB-1492\sqlipt;Initial Catalog=Bookings;Integrated Security=True;Pooling=False")
Dim entrclientid As String
Dim clid As New TextBox
clid = FormView1.FindControl("txtclientid")
entrclientid = clid.Text
Dim sql As String = "INSERT INTO BOOKING_DETAILS(CLIENT_ID,BOOKING_DATE,REGO,CHECK_IN_DATE,CHECK_OUT_DATE,ROOM_ID) VALUES(#ROOM_ID,#CHECK_OUT_DATE,#CHECK_IN_DATE,#CLIENT_ID,#BOOKING_DATE,#REGO)"
Dim cmdentry As New SqlCommand(sql, cnnentry)
cmdentry.Parameters.AddWithValue("#CLIENT_ID", clid.Text)
Dim curdate As New TextBox
curdate = FormView1.FindControl("txtdate")
cmdentry.Parameters.AddWithValue("#BOOKING_DATE", curdate.Text)
Dim rego As New TextBox
rego = FormView1.FindControl("RegoTextBox")
cmdentry.Parameters.AddWithValue("#REGO", rego.Text)
Dim textin As New TextBox
textin = FormView1.FindControl("textcheckin")
cmdentry.Parameters.AddWithValue("#CHECK_IN_DATE", textin.Text)
Dim textout As New TextBox
textout = FormView1.FindControl("textcheckout")
cmdentry.Parameters.AddWithValue("#CHECK_OUT_DATE", textout.Text)
Dim txtroomid As New TextBox
txtroomid = Session.Item("room_tpe")
cmdentry.Parameters.AddWithValue("#ROOM_ID", roomtype.Text)
cnnentry.Open()
strclid = cmdentry.ExecuteNonQuery()
cnnentry.Close()
End Using
End Sub
can somebody explain why i am getting this error?
the table data types are as follows:
Booking_ID int
Room_ID int
Check_In_Date nvarchar(MAX)
Check_Out_Date nvarchar(MAX)
Booking_Date nvarchar(MAX)
Client_ID nchar(11)
Rego nvarchar(6)
Room_Cost money
Thanks in advance
You are trying to insert data to a field which can not be held by defined datatype.
E.g : VARCHAR(3) can not hold 'TestData'.
In the table BOOKING_DETAILS check column datatypes.
How do I get a UserID from one database table (Users) to be inserted into another table (Ticket)? Both columns in each table has the same datatype (int). Please take a look:
Users
UserID
UserName
Password
FirstName
LastName
Email
Updated
Deleted
Ticket
TicketID
DateCreated
UserIDNum FK
FullName
Email
Subject
Message
Deleted
These are all of the codes involved:
Partial Public Class mysupport
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
MaintainScrollPositionOnPostBack = True
SetFocus(helpTopicDDL)
Else
SetFocus(fullNameTXTBOX)
End If
Dim sConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TrackTicketsConnectionString2").ConnectionString)
sConnection.Open()
If Session("Ticket") Is Nothing Then
Response.Redirect("SignIn.aspx")
Else
Dim cmdS As String = "Select * from Users Where Deleted='N' AND Username=#Username"
Dim cmdCheckEmail As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#Username", Data.SqlDbType.VarChar)
cmdCheckEmail.Parameters.Add("#Username", SqlDbType.VarChar)
cmdCheckEmail.Parameters.Item("#Username").Value = Session("Ticket")
Dim obj As Object = cmdCheckEmail.ExecuteScalar()
If obj IsNot Nothing Then
mailLBL.Text = Convert.ToString(obj)
End If
End If
sConnection.Close()
End Sub
Protected Sub submitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitBTN.Click
Dim sdConnection As String = ConfigurationManager.AppSettings("TrackTicketsConnectionString2")
Dim iRowCount As Integer
Dim cmdInsertTicket As New Data.SqlClient.SqlCommand
Dim conticket As New Data.SqlClient.SqlConnection
conticket.ConnectionString = sdConnection
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "Insert Into Ticket " _
& "( DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values( #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
'Dim appUserName As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.NVarChar)
'cmdInsertTicket.Parameters.Add(appUserName)
'cmdInsertTicket.Parameters.Item("#UserName").Value = User.Identity.Name
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
Dim appFullName As New Data.SqlClient.SqlParameter("#FullName", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appFullName)
cmdInsertTicket.Parameters.Item("#FullName").Value = fullNameTXTBOX.Text
Dim appEmail As New Data.SqlClient.SqlParameter("#Email", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appEmail)
cmdInsertTicket.Parameters.Item("#Email").Value = emailAddTXTBOX.Text
Dim appTicketType As New Data.SqlClient.SqlParameter("#TicketType", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appTicketType)
cmdInsertTicket.Parameters.Item("#TicketType").Value = helpTopicDDL.SelectedValue
Dim appSubject As New Data.SqlClient.SqlParameter("#Subject", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appSubject)
cmdInsertTicket.Parameters.Item("#Subject").Value = subjectTXTBOX.Text
Dim appMessage As New Data.SqlClient.SqlParameter("#Message", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appMessage)
cmdInsertTicket.Parameters.Item("#Message").Value = messageTXTBOX.Text
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
conticket.Open()
Try
iRowCount = cmdInsertTicket.ExecuteScalar()
statusLBL.Text = "Ticket has been submitted successfully."
Catch
statusLBL.Text = "Ticket has not been submitted. Please try again."
End Try
conticket.Close()
End Sub
What I really wanted is for a person's UserID to be stored in Ticket table after he has logged in to fill out a form and submitted it. I'm at a loss in how to pull the data from Users table to insert into Ticket table. Any help is much appreciated as I'm still learning.
EDIT:
Inserting the UserID into the Tickets table when adding a record first requires that you have access to the UserID value. You then need to pass this value in your INSERT statement.
Looks like we first need to retrieve the UserId. Since you are using FormsAuthentication we can retrieve the UserName from the User.Identity.Name object and use that as the value in our first query to retrieve the UserId.
Dim cmdS As String = "Select [UserID] from Users Where Deleted='N' AND UserName=#UserName"
Dim cmdGetUserId As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.VarChar)
cmdGetUserId.Parameters.Add("#UserName", SqlDbType.VarChar)
cmdGetUserId.Parameters.Item("#UserName").Value = User.Identity.Name
Dim obj As Object = cmdGetUserId.ExecuteScalar
Dim myUserId As Integer = Integer.Parse(obj)
Now that we have the UserId value for our current user we can modify our INSERT statement and parameters.
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "INSERT INTO Ticket " _
& "(UserID, DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values(#UserID, #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
Dim appUserId As New Data.SqlClient.SqlParameter("#UserID", Data.SqlDbType.Int)
cmdInsertTicket.Parameters.Add(appUserId)
cmdInsertTicket.Parameters.Item("#UserID").Value = myUserId
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
...
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
You can access authentication information through the User.Identity object once the user has been authenticated. Might also want to think about implementing a custom IIdentity class to store the UserID if you will need access to it often. Here's a good MSDN article about Custom Authentication: http://msdn.microsoft.com/en-us/library/ms172766(v=vs.80).aspx
UPDATE:
In regards to the comment below, you are retrieving the UserID because the SqlCommand is being executed with the ExecuteScalar method which returns the value of the first column of the first row. I would recommend taking a closer look at the SqlCommand object: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx and this ADO.NET primer on MSDN: http://msdn.microsoft.com/en-us/library/e80y5yhx(v=vs.80).aspx
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 web page with following fields
name,address,post
with three textboxes.I want to provide the search facility to the user.if user enter only the name and hit search it should search only by name, if user enter the values for all the textboxes it should query the database with all 3 values.like wise how can i write the sql query for all the searching possibilities?
select *
from Table1
where
(coalesce(#Name, '') = '' or Name = #Name) and
(coalesce(#Address, '') = '' or Address = #Address) and
(coalesce(#Post, '') = '' or Post = #Post)
I prefer this option for the query. If the user enters a value in only one of the fields, then pass a null to the parameter of the other respective fields.
Create PROCEDURE [dbo].[uspGetPeople]
#name varchar(50),
#Address varchar(200),
#Post varchar(5)
AS
SET NOCOUNT ON;
Select name, address, post
from tblPeople
where (name = #Name or #Name IS NULL) and
(address = #Address or #Address IS NULL) and
(post = #Post or #Post IS NULL)
A simple VB.NET example to call the stored procedure:
Dim strName As String = NameTextBox.Value
Dim strAddress as string = AddressTextBox.Value
Dim strPost as string = PostTextBox.Value
Dim strSQL As String = "uspGetPeople"
Dim strConn As String = "My.Database.ConnectionString"
Dim cn As New SqlConnection(strConn)
Dim cmd As New SqlCommand(strSQL, cn)
cmd.CommandType = CommandType.StoredProcedure
If not string.isnullorempty(strName) then
cmd.Parameters.AddWithValue("#Name", strName)
Else
cmd.Parameters.AddWithValue("#Name", dbnull.value)
End if
If not string.isnullorempty(strPost) then
cmd.Parameters.AddWithValue("#Post", strPost)
Else
cmd.Parameters.AddWithValue("#Post", dbnull.value)
End if
If not string.isnullorempty(strAddress) then
cmd.Parameters.AddWithValue("#Address", strAddress)
Else
cmd.Parameters.AddWithValue("#Address", dbnull.value)
End if
Dim dr As SqlDataReader
Using cn
cn.Open()
dr = cmd.ExecuteReader
While dr.Read
'process records returned
'dr("name")
'dr("address")
'dr("post")
End While
cn.Close()
End Using