I cannot use variable string in my SQL query using Oracle connection - asp.net

I have a simple code i am just trying to know if the given userid entered is already registered. So i write;
string a="somestring";
conn = new OracleConnection("Data Source=Home-PC;Persist Security Info=True;UserID=ali;Password=abc123;");
conn.Open();
OracleCommand cmd = new OracleCommand("select * from users where userid=#a", conn);
cmd.Parameters.AddWithValue("#a", a);
var data = cmd.ExecuteReader(); <-- Here it shows error *illegal variable name/number*
if (data.HasRows) return false;
else return true;
what am i doing wrong?

When you are using named parameters in an SQL statement referenced by an OracleCommand, you must precede the parameter name with a colon (:).
Try changing your command text from
OracleCommand cmd = new OracleCommand("select * from users where userid=#a", conn);
to
OracleCommand cmd = new OracleCommand("select * from users where userid = :a", conn);
cmd.Parameters.AddWithValue(":a", a);
and then execute you command as follows
OracleDataReader reader = cmd.ExecuteReader();

Related

select as sql and use in asp.net

i want select from my sql and create a session from one table field
string strquery = "select * from Registration where username=#username ";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#username", txt1_username.Text);
SqlDataReader nwReader = cmd2.ExecuteReader();
string cus = "";
if (nwReader.Read())
{
cus = nwReader["customer_id"].ToString();
}
nwReader.Close();
connection.Close();
Session["customer_id_se"] = cus.ToString();
Response.Redirect("Wedding.aspx");
my problem is: i can't use that field and use in session
You are doing few mistakes, let me point them first(obviously it will solve the issue too).
As i mentioned in the comment, "you are creating connection2 and
opening connection using connection.Open(); it should be either
connection2.Open(); or remove connection2 from the block.
The .Parameters.Add() method expect SqlDbType specify them and add its value using the following statement.
cmd2.Parameters.Add("#username",SqlDbType.VarChar).Value = txt1_username.Text;
There may be situations where nwReader will not having any rows(query returns no result). Accessing value from it in such situation will give you exception as "Invalid attempt to read when no data is present", So you need to check for existence of data in the Reader before accessing it.
That is you should use like the following:
SqlDataReader nwReader = cmd2.ExecuteReader();
string customerId = String.Empty;
if (nwReader.HasRows)
{
customerId = nwReader["customer_id"].ToString();
}
4. customerId is already a string so you need not to convert it again using .ToString() before assigning to the session. So the complete scenario can be coded as like the following:
string strquery = "select * from Registration where username=#username";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#username", SqlDbType.VarChar).Value = txt1_username.Text;
SqlDataReader nwReader = cmd2.ExecuteReader();
string customerID = "";
if (nwReader.HasRows)
{
customerID = nwReader["customer_id"].ToString();
}
nwReader.Close();
connection.Close();
Session["customer_id_se"] = customerID;
Note :-
If nwReader.HasRows is false means there is no such record for the
specific username, in this case customerID and hence
Session["customer_id_se"] will be blank.
Updates as per HansKesting's comment,
Select * will fetch the entire rows which satisfies the condition in the Where clause. If you requires only a single value and you are sure that the result will be either empty or a single value then you can use SELECT column_name from ... and in such situations use ExecuteScalar to get the value.

There is no row at position 0, exception

I am having a problem while login, the registered user's name, email and password is saved in the database and the email is the username. When i am logging through email and password it shows the error "There is no row at position 0."
Here's my code :
con.Open();
cmd = new SqlCommand("select * from userinfo where username='" + t1.Text.ToString() + "' and password='" + t2.Text.ToString() + "'", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
con.Close();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #username AND password = #password", con);
cmd.Paramater.AddWithValue("#username", t1.Text.ToString());
cmd.Paramater.AddWithValue("#password", t2.Text.ToString());
con.open();
SqlDataReader dr = cmd.ExecuteReader();
dr.read();
if(dr.hasRows){
Session["name"] = dr["username"].ToString();
}
con.close();
Try not to throw variables into a sql command. SQL injection and all. Try and pass the paramater
Because reason is the no one record found in Db same as a passing username and password and you can directly access so its give exception. Please add one if condition below like.
con.Open();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #username AND password = #password", con);
cmd.Paramater.AddWithValue("#username", t1.Text.ToString());
cmd.Paramater.AddWithValue("#password", t2.Text.ToString());
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
if(ds.Tables["abc"].Rows.Count>0)
{
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
}
con.Close();
The exception is because there are no records in that table.
There are no rows, so there is no Rows[0].
Try something like this:
using (var con = new SqlConnection(connectionString))
{
con.Open();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #1 AND password = #2", con);
cmd.Paramater.AddWithValue("#1", t1.Text);
cmd.Paramater.AddWithValue("#2", t2.Text);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
if(ds.Tables["abc"].Rows.Any())
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
con.Close();
}
You should use parameters when constructing SQL queries to avoid injection attacks.
Don't forget that SqlConnection is IDisposable, so should be in a using statement (you might already be doing this, but i've included it here just in case).
It also looks like the user's password is being compared to the input from a TextBox (or a similar control)? If so, the user's password should not be stored in plain text in the database as this is a security issue. Consider hashing the stored password, doing the same with the user's input, and comparing that instead.
This wasn't part of the question, I know, but worth pointing out just in case.

Return a string Value from SQL Server stored procedure

I have the following method and stored procedure.
My question is how to return a string value from stored procedure to use in addStaffName method ?
public string addStaffName()
{
string staffName = string.Empty;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection SqlCOn = new SqlConnection(sConnectionString);
SqlCommand SqlCmd = new SqlCommand();
SqlCOn.Open();
SqlCmd.Connection = SqlCOn;
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.CommandText = "FetchStaffName";
SqlCmd.Parameters.AddWithValue("email", email);
//???
return staffName;
}
create procedure fetchStaffName
#email varchar(100)
AS
begin
select (employeeName)
from employee
where email = #email
end
If you can be sure that you'llonly ever get one row, one column as a result set - then you can use .ExecuteScalar() on your SqlCommand like this:
string staffName = string.Empty;
string sConnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
using (SqlConnection sqlCon = new SqlConnection(sConnectionString))
using (SqlCommand sqlCmd = new SqlCommand("FetchStaffName", sqlCon)
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#email", email);
sqlCon.Open();
staffName = sqlCmd.ExecuteScalar().ToString();
sqlCon.Close();
return staffName;
}
I also put the usage of SqlConnection and SqlCommand into using() { ... } blocks which is the recommended best practice for anything that's deriving from IDisposable to ensure proper disposal of the objects after their use
Consider to make fetchStaffName a scalar function rather than stored procedure. By definition stored procedures are required to perform a set of actions with data. Scalar function guarantees there will be exactly one output value for the set of input values.
CREATE FUNCTION fetchStaffName (
#email VARCHAR(100)
)
RETURNS VARCHAR(?) --Place the length of employeeName field instead of ? symbol.
BEGIN
RETURN (SELECT employeeName FROM employee WHERE email = #email)
END
And then your .NET code transforms into the following:
using (SqlConnection SqlCOn = new SqlConnection(sConnectionString))
{
SqlCommand SqlCmd = new SqlCommand("SELECT fetchStaffName(#email)", SqlCOn);
SqlCmd.CommandType = CommandType.Text;
SqlCmd.Parameters.AddWithValue("#email", email);
SqlCOn.Open();
staffName = (string)SqlCmd.ExecuteScalar();
}
As you can see CommandType changed from StoredProcedure to Text. I also wrapped the work with SqlConnection object into using construction to dispose its resources and close automatically.

Update in ASP.NET

I am using this code snippet to update values in my database :
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;Integrated Security=True");
string str = "sama#yahoo.com";
SqlCommand com2 = new SqlCommand("select [user_Account] from User in str where [user_Email]=sama#yahoo.com", con);
SqlCommand com = new SqlCommand("update User set [user_Account]=? WHERE [user_Email=#em]", con);
com.Parameters.AddWithValue("user_Account",str);
com.Parameters.AddWithValue("#em",str);
con.Open();
com.ExecuteNonQuery();
com2.ExecuteNonQuery();
con.Close();
but I get this error
Incorrect syntax near the keyword 'User'.
Line 40: com.ExecuteNonQuery();
"User" is a reserved word in SQL. Wrap the name of the table in square brackets to specify that it's the name of something:
[User]
Why are you using two separate SqlCommand objects?? Absolutely not needed..... I would try to either UPDATE or SELECT - don't mix two totally separate operations into a single call....
Also: you should use parametrized queries to avoid SQL injection attacks, and you should put your SqlConnection and SqlCommand objects into using blocks - try this:
string updateStmt =
"UPDATE dbo.[User] SET [user_Account] = #AccountValue WHERE [user_Email] = #UserEMail;";
using(SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;Integrated Security=True"))
using(SqlCommand _cmd = new SqlCommand(updateStmt, con))
{
_cmd.Parameters.Add("#AccountValue", SqlDbType.VarChar, 100).Value = str;
_cmd.Parameters.Add("#UserEMail", SqlDbType.VarChar, 100).Value = str;
con.Open();
_cmd.ExecuteNonQuery();
con.Close();
}

How can I execute multiple database requests in ASP.NET C#?

In every ASP.NET application I have written, I would make number of request to the database before outputting the information onto the web page.
For example:
var DataTable1 = GetDataTable("Select * From Customers");
var DataTable2 = GetDataTable("Select * From Products");
var DataTable3 = GetDataTable("Select * From Orders");
As far as I'm aware, the code above would make 3 separate trips to the database and would do them one after the other.
Is there anyway I can gather together my parameterized SQL statements and make only 1 trip to the database server?
var SqlString = "SELECT * FROM Customers; SELECT * FROM Products; SELECT * FROM ORDERS;");
var ds = GetDataSet(SqlString);
var DataTable1 = ds.Tables(0);
var DataTable2 = ds.Tables(1);
var DataTable3 = ds.Tables(2);
My solution:
SqlConnection con = new SqlConnection("Server=CLASS-III-WKS10\\SQLEXPRESS;Initial
Catalog=wind;Integrated Security=True");
int[] id=new int[9];
int i = 0;
page_load()
{
con.Open();
SqlCommand cmd = new SqlCommand("select *from windmill", con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
id[i] = rd.GetInt32(9);
i++;
//MessageBox.Show(id.ToString());
}
rd.close();
SqlCommand cmd1 = new SqlCommand("Update windmill set State='Stopped',PmState='Not Available'where Id=0", con);
cmd1.ExecuteNonQuery();
}
Use semi-colons to separate SQL statements and reader.NextResult to get each set. Your code will end up looking something like this.
Using con As New SqlConnection
Using cmd As New SqlCommand("Select * From Customers; Select * From Products; Select * From Orders")
Using reader = cmd.ExecuteReader
Dim dt1 As DataTable
dt1.Load(reader)
reader.NextResult()
Dim dt2 As DataTable
dt2.Load(reader)
reader.NextResult()
Dim dt3 As DataTable
dt3.Load(reader)
End Using
End Using
End Using
Create a Thread class and place a method in that class which accept string query as input:
then create a Thread object and start the object.
Check this out http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx

Resources