What does the “?” symbol do in SQL? - sql

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.

Related

Data type mismatch in criteria expression. whats wrong?

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.

InsertStatement using SelectStatement in asp.net

I am trying use insert but as one of parameters use result of select statement
try {
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RentCarConnectionString"].ConnectionString);
conn1.Open();
string selectQuery = "Select IDOsoby from Klienci Where Email = #Semail ";
string insertQuery = "insert into Wypozyczenia (IdOsoby, IDCAR, DataWypozyczenia) values (#idOs, #idcar, #data)";
string updateQuery = "Update Samochody SET CzyDostepny = 'False' Where IDCAR = #idCar";
SqlCommand com1 = new SqlCommand(selectQuery, conn1);
SqlCommand com2 = new SqlCommand(insertQuery, conn1);
SqlCommand com3 = new SqlCommand(updateQuery, conn1);
com1.Parameters.AddWithValue("#Semail", Session["New"]);
com2.Parameters.AddWithValue("#idOs", selectQuery);
com2.Parameters.AddWithValue("#idCar", Session["S_polka"]);
com3.Parameters.AddWithValue("#idCar", Session["S_polka"]);
com2.Parameters.AddWithValue("#data", DateTime.Today.ToShortDateString());
com1.ExecuteNonQuery();
com2.ExecuteNonQuery();
com3.ExecuteNonQuery();
conn1.Close();
}
catch(Exception ex)
{
}
Code working but into Wypozyczenia table It has been added IdOsoby as "It has been added". Please help how can I fix it ?
By this way, Combine the separate Insert and Select queries. Just use Insert into..Select syntax
insert into Wypozyczenia (IdOsoby, IDCAR, DataWypozyczenia)
Select IDOsoby, #idcar, #data from Klienci Where Email = #Semail

sql query error incorrect syntax

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";

How to use SQL parameters with NpgsqlDataAdapter?

Is it possible to use parameters together with NpgsqlDataAdapter, as I can do with NpgsqlCommand:
string sql = "SELECT * FROM tbl_student WHERE name = #val";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("#val", name);
I have this code, which displays the information about the students i a gridview:
string sql = "SELECT * FROM tbl_student WHERE studentname = '" + name + "'";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds); // filling DataSet with result from NpgsqlDataAdapter
dt = ds.Tables[0]; // select select first column
GridView1.DataSource = dt; //connect grid to DataTable
GridView1.DataBind();
My question is: can I somehow use parameters (as in the example above) instead of using '" + name + "' in the SQL?
I have learned always to use parameters, is it also necessary when using NpgsqlDataAdapter?
Thank you.
I used to have the same question and this is what I came up with:
string sql = "SELECT * FROM tbl_student WHERE studentname = #param";
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
command.Parameters.Add("#param", textBox_studentname.Text); //add the parameter into the sql command
DataTable dt = new DataTable();
//load the DataReader object of the command to the DataTable
dt.Load(NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection));
GridView1.DataSource = dt;
You could read this and this.

How to pass integer variable in sql query

int no = FormView1.PageIndex;
Query:-
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
You have to add a parameter:
int no = FormView1.PageIndex;
SqlCommand cmd =
new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
// Set the parameter up before executing the command
cmd.Parameters.Add("#no", SqlDbType.Int);
cmd.Parameters["#no"].Value = no;
You need to add a SqlParameter to the SqlCommand:
int no = FormView1.PageIndex;
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionNo = #no", cn);
cmd.Parameters.AddWithValue("#no", no);
use an array of System.Data.SqlClient.SqlParameter
SqlCommand cmd(...);
SqlParameter[] inQueryParameters = ...;
cmd.Parameters.AddRange(inQueryParameters);
Use SqlParameters. See the example below.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
You can use this code:
SqlCommand ageCom = new SqlCommand("select age_phase from PatintInfo where patient_ID=#ptn_id", con);
ageCom.Parameters.Add("#ptn_id",SqlDbType.Int).Value=Convert.ToInt32(TextBox1.Text);
It had worked in my program correctly.