Compare value of a string to Database value - asp.net

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.

Related

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.

How can I select a single column from a table in SQL Server & put that value into a variable?

I have a table Registration with many columns. I need to get customer_id and put that value into a variable for use that in a session for moving & use between ASP Webforms. How can I do this?
You can use ExecuteScalar method to get single column value. Below is a very basic example of how to get single column value.
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("select Customer_id from Registration", con);
con.Open();
string id = cmd.ExecuteScalar().ToString();
}
Here is how you can store the value in session
Session["CustomerID"] = id;
And here is how you can retrieve the value on second page
int ID = 0;
int.TryParse((string)Session["CustomerID"], out ID);

What is wrong with the following query?

I have a table containing name, surname and email. I want to retrieve them from the table and so i write:
if (LoginAs.SelectedValue == "Administrator")
{
string result;
string query = "Select * from AdminTable where ID='"+ idBox.Text +"'";
cmd1 = new SqlCommand(query, con);
result = Convert.ToString(cmd1.ExecuteScalar());
Response.Redirect("Admin.aspx");
//Admin user = new Admin(idBox.Text, "Active", mail, firstName, LastName, passwordBox.Text);
}
The problem is, it only returns the name field of the specified row even though i wrote "Select *". What is wrong here?
ExecuteScalar returns just the first column of the first row, and ignores the rest.
So you should use ExecuteReader method. An example from MSDN:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
Note that the while (reader.Read()) checks whether your query returned (more) results and positions the cursor on the next record, that you can then read. This example prints the first column's value.
The using statement makes sure the connection is closed after use, whatever happens.
Also, don't build your query directly with input from the user (such as the value of a TextBox), use parameters instead to prevent SQL injection attacks.
You must try ExecuteReader() instead of using ExecuteScalar()
ExecuteScaler is used in situation where we have to read a single value.eg:
select count(*) from tablename.
while
ExecuteReader is used for any result set with multiple rows/columns
(e.g., SELECT * from TableName)
Sample code:
string myQuery="Select * from AdminTable where ID=#myid";
SqlCommand cmd=new SqlCommand(myQuery,conn);
cmd.Parameters.AddWithValue("#myid", value);
conn.Open();
SqlDataReader dreader;
dreader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dreader.Read())
{
string Value1= dreader["COl1"].ToString();
string Value2= dreader["COl2"].ToString();
}
dreader.Close();
Always use parameterized Query
You may try cmd1.ExecuteReader() instead.

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.

System.Data.SqlClient.SqlException: Invalid column name

Trying to do a recordset, I just want one column of data, but this code is giving me an error.. I'm an ASP.NET newb, can anyone help?:
System.Data.SqlClient.SqlException: Invalid column name
'CustomerName'.
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
string CustomerName = "CustomerName";
}
}
String EncCustomerName = Encrypt(CustomerName.Replace(".", "").Replace("-", ""),"1");
Question #2: How do I bind the database content to the CustomerName string? It seems like its only returning "CustomerName" as the value for CustomerName string.. I would like it to return the database data for CustomerName string.. Help?
Suggested to use a ExecuteScalar, so i modified the request to this
using (var con = new SqlConnection(DB.GetDBConn()))
using (var cmdContrib = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID=" + ThisCustomer.CustomerID, con))
{
con.Open();
string CustomerName = cmdContrib.ExecuteScalar();
}
And i Get this error:
"string CustomerName = cmdCust.ExecuteScalar();"
CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
To answer your second question:
// Set it here so you can access it outside the scope of the using statement
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
while (dr.Read())
CustomerName = dr["CustomerName"].ToString();
}
}
}
If you're sure you'll only get one CustomerName result, using a DataReader is a bit of an overkill.
SqlCommand.ExecuteScalar Example
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID = " + Customer.CustomerID, con);
cmd.CommandType = CommandType.Text;
con.Open();
CustomerName = Convert.ToString(cmd.ExecuteScalar());
}
SqlCommand.ExecuteScalar Method
Additional Info
ExecuteScalar returns an object, so you'll need to convert the returned value to the proper type (in this case, string).
Also, you should declare your CustomerName value outside of the using blocks (as I did in my example) - otherwise it will be scoped to the using blocks and not available outside of them.
It means that either CustomerName or CustomerID is not a valid column within your database. Check your table again.
Make sure you are trying to connect correct database.
See CustomerName column should be in Customer table. check spelling also
First, debug and check the value of:
DB.GetDBConn()
You will verify that you are going to the same in Studio as you are in the program.
I think it is the spelling somewhere between the db and your code.
Once you get past the error, you need to fix this:
{
string CustomerName = "CustomerName";
}
You are not accessing the reader, try some kind of tutorial for that stuff.
Try doing a select * from customer where ... and put a breakpoint on your using datareader statement. Then use quick-watch on the datareader object to investigate the columns exposed in the recordset.
Or you could run the select statement on your db of choice to ensure that the column name is the same.
I agree with Madhur above, your column name is not spelled correctly. Or you are not connecting to the correct db.
Hope this helps

Resources