how to compare a value from database with the textbox value - asp.net

I am using sql server 2005 and visual stdio 2008
i have a textbox in my page as txtEmailId
i want to compare this value in database with email_id column[it is a primary key]
to avoid inconsistence in database on a button click with out using custom validator

There are several ways.
1: Do a db query using sqlcommand like below:
SqlDataReader reader = null;
SqlConnection conn = new SqlConnection("Yourconnectionstring");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from yourtable where email_id=#emailid", conn);
cmd.Parameters.AddWithValue("#emailid",txtEmail.Text);
reader = cmd.ExecuteReader();
if(reader!=null && reader.HasRows){
//email exists in db do something
}

My syntax might be off, but is this what you are looking for?
if txtEmailID.Text == email_id
performActionA;
Else
performActionB;

SOLUTION :>
ValidateQuery = "Select [Email_Id] from Sign_Up where (Email_Id = '"+txtEmailId.Text+"')";
SqlCommand Validatecmd = new SqlCommand(ValidateQuery, con);
String validate_email;
validate_email= (String)Validatecmd.ExecuteScalar();
if (validate_email != null)
{
lblValidateEmail.Text = "YOUR EMAIL ID IS REGISTERD TRY DIFFERENT EMAIL ID ";
}
else
{
// DO WHAT EVER U WANT
}</code>

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

My SqlDatareader was not working

I have a code for fetching customer_id and I use a SqlDataReader for reading customer_id from SQL Server. I test witch using breakpoint and step by step debugging and I understand the SqlDataReader condition was not compile and compiler jump straight in to the connection.close line:
string strQuery = "select customer_id from Registration where username=#username and password=#password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
string customer_id = cmd.ExecuteScalar() as string;
connection1.Close();
if (customer_id == null)
{
Messages myMsg = new Messages();
myMsg.CreateMessageAlert("The User does not Registered or your using incorect username or password");
}
else {
Session["customer_id"] = customer_id;
}
Although the issue is not very clear, you can try to revise the code taking following into account:
There is no need to open/close db connection for every sql query in a method. Open it once, execute all queries, close. That will make code clear and faster.
As you take connection from somewhere else, make sure it is closed before you open it (Example: Check if SQL Connection is Open or Closed)
You run 2 queries and in both cases you get only 1 result (select count(*), select customer_id). Why then in first case you do ExecuteScalar() and ExecuteReader() in the other?
The other thought is there is no need to have 2 SqlCommand(), etc if you need to return results of 2 queries. Read about Retrieving Multiple Result Sets using NextResult
And last but not least - it seems you need to check if user is already registered and if true, get his id. Why not do it in one shot? The second query is good for both cases - if user does not exist, query will not return any result, if he does - his id will be returned. Doing this way, you would need only one query and less coding.
UPDATE:
The updated code looks more clear and straightforward, but you didn't get the point of my last comment. If you select count(customer_id) you get a count that you don't need. Why not simply select customer_id and check if it was returned or not?
Example:
//string strQuery = "select count(customer_id) from Registration where username=#username and password=#password";
string strQuery = "select customer_id from Registration where username=#username and password=#password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
//int intRowCount = (int)cmd.ExecuteScalar();
string customer_id = cmd.ExecuteScalar() as string;
//txt1_username.Text = intRowCount.ToString(); <-- What's this?
connection1.Close();
//if (intRowCount == 1)
if (customer_id == null)
{
// user does not exist, because sql returned no rows
... <-- do something here
} else {
Session["customer_id"] = customer_id;
}
UPDATE #2:
To troubleshoot
Make sure txt1_username.Text and txt2_password.Text have expected values. It could be that you reset the Text somewhere and that could be the reason why the query returned no result. Try to hardcode the value in the code, for example,
cmd2.Parameters.AddWithValue("username", "admin");
cmd2.Parameters.AddWithValue("password", "123");
Copy-paste entire sql in Sql Server Management Studio (or other tool) and run it from here to ensure what result it returned.
Make sure you execute it against correct database (maybe you have different databases with same tables where data is different).
This is because your username is no longer the username. It is actually 1 because of the line
int intRowCount = (int) cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString(); <-- RED FLAG
So in the inside the If, you are actually running
SELECT customer_id FROM registration WHERE username=1 and password=my_password
Comment line 15 and you should do fine.
updated
string strQuery = "select count(*) from Employee where FullName=#username";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
int intRowCount = (int)cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString();
if (intRowCount == 1)
{
string strquery = "select customer_id from Registration where username=#username and password=#password";
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.AddWithValue("username", txt1_username.Text);
cmd2.Parameters.AddWithValue("password", txt2_password.Text);
SqlDataReader reader = cmd2.ExecuteReader();
if (reader.Read())
{
string customerID = reader[0].ToString();
}
}
connection.Close();`
This is complete solution for your issue.
Do not need to open connection everytime. just make sure, connection is being closed once it's used.

multiple SQL commands. Good style?

I got an asp.net application running perfectly fine. in my code i have the following lines
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con);
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con);
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
con.Open();
newGenreId = (int)getGenreId.ExecuteScalar();
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
i know database connections are valuable resources and i should be careful when using them. (open as late as possible and make sure they will be closed aswell)
My question now is this code considered bad style because im opening the connection then have as sql query to get an ID and then have another sql query to insert a record.
thanks you!
If you convert to using stored procedure, you can eliminate 1 round trip, therefore reducing network traffic and possibly increase performance.
using (SqlCommand cmd = new SqlCommand("Update_tblSong", con);
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#newGenre", newGenre);
cmd.Parameters.AddWithValue("#newTitle", newTitle);
cmd.Parameters.AddWithValue("#newArtistId", newArtistId);
cmd.Parameters.AddWithValue("#songId", songId);
cmd.ExecuteNonQuery();
}
Proc will be like this, I estimated on your variable size.
CREATE PROC Update_tblSong
(
#newGenre VARCHAR(25)
,#newTitle VARCHAR(50)
,#newArtistID INT
,#songID INT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #NewGenreID INT;
SELECT #NewGenreID = ID
FROM tblGenre
WHERE Genre = #newGenre;
UPDATE tblSong
SET Title = #newTitle
,ArtistId = #newArtistId
,GenreId = #NewGenreID
WHERE ( ID = #songId )
END;
Overall your code flow seems fine, you are using a single connection to execute multiple (related) commands.
You can improve it further with enclosing your command objects in using statement. Since they implement IDisposable interface, just like your connection object.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
using (SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con))
{
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
newGenreId = (int)getGenreId.ExecuteScalar();
}
using (SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con))
{
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
}
Why not use a single query with a subquery for your SQL?
UPDATE tblSong SET Title = #newTitle, ArtistId = #newArtistId, GenreId = (Select top 1 ID from tblGenre WHERE Genre=#newGenre ORDER BY Genre) WHERE (ID = #songId);

Compare value of a string to Database value

I have to compare a value in a string array to that of a particular column in a database. How do i do this ?
public void setvisibility(string user_ID)
{
SqlDataReader reader = null;
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString);
connection.Open();\
SqlCommand cmd = new SqlCommand("Select * from Admins );
I need to compare the value of user_ID to the only column in the Admins table !
Here's how you can do it:
using( SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("Select 1 from Admins where User_ID=#userid",connection );
cmd.Parameters.AddWithValue("#userid",user_ID);
SqlDataReader reader= cmd.ExecuteReader();
if(reader.HasRows)
{
//user id found
}
}
This method uses a parametrized queries, which are safer than the option given in the answer by Tony since his is prone to SQL Injection attacks.
BTW: you mention "string array" in your question, yet your code only shows a single string as parameter. What did you mean by that?
sqlcommand("SELECT * FROM Admins WHERE column = " & user_ID );
That should work. What that does is it returns the value in the column if it is the same as the user_ID. Basically, if your query returns a value you have a match, if not then you don't.

using the querystring parameter in my where clause to generate insert operation

here,using request.Querystring i find the companyname and job title of particular Job.when user logsin using username in texbix.i want the Companyname,jobtitle and username in the same row of a table.But when i generate my query it inserts the (companyName & jobtitle) in the first row and username in second row.How can i fulfill my task.Some people said,i have to keep the companyname and jobtitle in a variable...then execute.
is it a parfect solution?
if it is,how can i do that?
code:
protected void ButtonApply_Click(object sender, EventArgs e) {
String str = Request.QueryString.Get("JobNo");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CompanyName,JobTitle) select CompanyName,JobTitle from Jobs where JobNo='"+str+"'" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
try {
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("ApplyJob.aspx?JobNo="+str);
}
in the apply.aspx i have following code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CandidateInformation) Values (#CandidateInformation)" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation", TextBoxaun.Text);
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
Inserting two times will always result in two new rows.
You can do it all in the first insert statement:
string apply = "INSERT INTO Company (CompanyName,JobTitle, CandidateInformation) select
CompanyName,JobTitle, #CandidateInformation from Jobs where JobNo=#JobNo ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation",
TextBoxaun.Text);
insertApply.Parameters.AddWithValue("#JobNo", str);
try
{
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
}
Then you won't need the second page.
Use
Update Company Set CandidateInformation = #CandidateInformation where JobNo='"+str+"'" ;
instead of
string apply = "INSERTINTO Company (CandidateInformation) Values
(#CandidateInformation)" ;
If you will use Insert statement again, then it will always create new record in the table.
Update is used to update an already existing record of the table.

Resources