i am trying the below query but i am getting error like incorrect syntax at SqlDataReader reader = command.ExecuteReader .. please correct me where i am wrong
string querystring = "SELECT ImageName FROM dbo.ProfilePic WHERE UserName = #UserName & IsActive = 'Y' order by ID Desc";
SqlCommand command = new SqlCommand(querystring, con);
command.Parameters.AddWithValue("#UserName", Session["UserName"].ToString());
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",
reader[0]));
ViewBag.ProfilePic = reader[0];
}
reader.Close();
updated with all suggested answers
SQL doesn't need the double equal signs.
SELECT ImageName FROM dbo.ProfilePic WHERE Username = #UserName
in SQL you don't need to use double equal sign to compare values and && is wrong, then this is wrong:
string querystring = "select ImageName from dbo.ProfilePic where UserName == #UserName && IsActive == 'Y' order by ID descending";
and this is true:
string querystring = "select ImageName from dbo.ProfilePic where UserName = #UserName AND IsActive = 'Y' order by ID desc";
string querystring = "select ImageName from dbo.ProfilePic where UserName =
#UserName AND IsActive = 'Y' order by ID DESC";
// on sql compare oprator not need to '==' sign
SqlCommand command = new SqlCommand(querystring, con);
command.Parameters.AddWithValue("#UserName", Session["UserName"].ToString());
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",
reader[0]));
// when you assign reader value to any object you must assign while DataReader read not after DataReader close
ViewBag.ProfilePic = reader[0];
}
reader.Close();
EDIT
try
string querystring = "select ImageName from dbo.ProfilePic where UserName like '#UserName' AND IsActive = 'Y' order by ID DESC";
Related
how do I put an int variable in sql?
int x = Convert.ToInt32(Session["id"]);
string MySQL = #"UPDATE users SET
email = '"+Request.Form["email"]+"', pname =
'"+Request.Form["pname"]+"', accountname=
'"+Request.Form["accountname"]+"', pid = '"+Request.Form["pid"]+"', age =
'"+Request.Form["age"]+"',passw = '"+Request.Form["passw"]+"' where
id='x';";
Please don't use concatenated values in your SQL command. You are exposing your application to SQL Injection Attacks. Read more here.
Use SqlParameters instead. It is the proper way to do and safer when you are running sql commands against your database from your application.
If a value is int covert it to integer:
command.Parameters.AddWithValue("#id", int.Parse(Request.Form["id"]));
Here is a example of how to use parameters.
string mySql = #"UPDATE users SET email = #email, pname = #pname, accountname = #accountname, pid = #pid, age = #age, passw = #passw where id = #id;";
string connectionString = "Server=localhost\\SQLEXPRESS;Database=[your database];User Id=sa;Password=[your password];";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(mySql, connection);
command.Parameters.AddWithValue("#email", Request.Form["email"]);
command.Parameters.AddWithValue("#pname", Request.Form["pname"]);
command.Parameters.AddWithValue("#accountname", Request.Form["accountname"]);
command.Parameters.AddWithValue("#pid", Request.Form["pid"]);
command.Parameters.AddWithValue("#age", int.Parse(Request.Form["age"]));
command.Parameters.AddWithValue("#passw", Request.Form["passw"]);
command.Parameters.AddWithValue("#id", int.Parse(Request.Form["id"]));
connection.Open();
command.ExecuteNonQuery();
}
More about SqlCommand here.
I have the following code that is comparing a hash value and username to the corresponding hash value and username in a local database (App_Users3)
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT Username, Hash FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
// savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value = savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show(" Query successful.. something matched.. ");
// change page.. load a profile?
}
It doesn't throw any errors but I don't understand why the messagebox isn't showing up.
ExecuteNonQuery returns the rows affected by modifying data statements (insert, update, delete). You should use ExecuteScalar for such select statements, and for example return the user's ID value. If you want to return more than one value (either multiple rows or multiple columns), you should use ExecuteReader.
Here is your code modified to return UserID of the matched user.
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT UserId FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
//savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value= savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteScalar() != null) {
MessageBox.Show(" Query successful..something matched.. ");
//change page.. load a profile?
}
}
example
SELECT pathName+
[fileName]+
fileExtension AS fileName
FROM BatchCompaniesPaths
WHERE batchID = ? AND pathType = ?;
If you are firing the query from a C# like programming language then ? must be a parameter holder, you need to pass sqlparameter for that place.
For example :
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
so in the above code the ? is replaced by #id when the query is fired on database.
I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.
I am storing an image in a table in varbinary(max) format, actually first time it will be empty, I am checking whether it is empty of not but while checking for null field I am getting any exception stating invalid cast so can any one suggest what is the problem with this.
code sample is
con = new SqlCeConnection(CommonClass.ConnectionStringStartup);
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Signature,UserId FROM UserMaster Where " +
" LoginName = '" + UserName + "' " +
" AND Password = '" + Password + "'";
cmd.CommandType = CommandType.Text;
// MessageBox.Show(UserName);
SqlCeDataReader dr;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
if (dr.IsDBNull(0))
SignLoaded = false;
else
SignLoaded = true;
}
Thanks in advance
With regards
Bharath kumar
To me, it looks like this should work?
Have you tried Convert.IsDbNull( dr.GetValue(0))?
Otherwise I can only suggest using dr.GetValue(0) and look at the result.
Cheers