This is the page behind code where it have error
if (Session["username"] != null)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString;
string sql1 = "Select pemgrp from Profile where userID = '" + Session["username"].ToString() + "'";
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DataTable dt = new DataTable();
cmd.CommandText = sql;
cmd.Connection = con;
//open connection and execute command
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
lb_classmates.Text = dr[0].ToString();
}
}
However, when i run, it give me this error :
Incorrect syntax near the keyword 'where'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'where'.
As you are using sub-query therefore this
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
and you should be using Parametereized queries to avoid SQL injection.
I think It should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
instead of
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
I would strongly recommend you to use parametereized queries
No One's answer is of course right.
If you want to use a subquery in a query, you should use IN (Transact-SQL)
Determines whether a specified value matches any value in a subquery
or a list.
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also consider to use using to dispose your SqlConnection.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString))
{
connection.Open();
string sql1 = "Select pemgrp from Profile where userID = #username";
string sql = "Select studname from Profile where pemgrp IN (" + sql1 + ")";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#username", Session["username"].ToString());
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//
}
}
You should use parameterized query something llike this
string sql = "Select studname from Profile where pemgrp = #p1";
and to pass parameter
command.Parameters.AddWithValue("#p1",sql1);
Related
I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.
I want to get the value of the Encrypted password into a string variable. but I am getting the whole query.
Here is my code:-
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
In strpassword i get the whole query.
But in Toad the result is as
F52377D5FFB1A47F
how to get that in oracle?
When you write
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
Then you are simply displaying the string value as you are not executing the SQL which is present inside the string.
What you are looking for is the result of the SQL which is present inside the string. To get the result of the SQL stored inside the string you need to execute it.
You can try like this:
string queryString = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader[0]));
}
}
finally
{
reader.Close();
}
}
As commented above, your query is prone to SQL Injection. A better way is to use paramterized query to get rid of it. Something like
string sql = "select sys.get_enc_val (#myvar) from dual";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("myvar", txtpassword.Text);
this is my code:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=MSDAORA;Data Source=data;Password=ss8_pakhsh;User ID=SHIFTS_N";
con.Open();
int MAXID = 1175;
MAXID++;
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(" + MAXID + ",'"
+ textBox1.Text +
"', SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME="+comboBox1.Text;
OleDbDataAdapter oda = new OleDbDataAdapter(sqlcommand, con);
oda.Fill(dt);
con.Close();
while i running it ,gets this error :
One or more errors occurred during processing of command.
i think my query has problem because when i enter it on TOAD editor(for oracle) gets me this error:
ORA-00936: missing expression
You were missing quotes and paranthesis in your query.
SQL Injection Alert
To avoid this you should use Parameterized queries as like follows
string sqlcommand ="INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID)
VALUES(?,?,SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=?)";
OleDbConnection oledbConnection = new OleDbConnection(con);
OleDbCommand oledbCommand = new OleDbCommand(sqlcommand , oledbConnection);
oledbCommand.Parameters.AddWithValue("?", txtquotationno.Text);
oledbCommand.Parameters.AddWithValue("?", cmbjobcode.Text);
oledbCommand.Parameters.AddWithValue("?", comboBox1.Text);
OleDbDataAdapter oda = new OleDbDataAdapter(oledbCommand);
DataTable dt= new DataTable();
oda.Fill(dt);
You need to put your select query in braces as you are selecting this from another table so this shoould be in (). Also Department_Name looks of type varcharso its value should be in single quotes. Change your query like this.
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(" + MAXID + ",'"
+ textBox1.Text +
"',(SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME='"+comboBox1.Text+"'"));
Also use parameterized query to prevent sql injection.
I'm trying to get the user's details from a database to show in some text boxes; however there seems to be a problem with my code. The following error keeps appearing:
syntax error (comma) in query expression
This is the complete code:
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbDataReader reader;
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---retrieve user's particulars---
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1);
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
reader.Read();
// ---display user's particulars---
textBox2.Text = reader["SSN"].ToString();
textBox3.Text = reader["FirstName"].ToString();
textBox4.Text = reader["LastName"].ToString();
}
Here
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1);
so internally .ToString method would have been called on textBox1 and your commandText would have become
SELECT * FROM Enroll WHERE ID=System.Windows.Forms.TextBox, Text:
Hence the error.
What you probably mean is the text in the textbox
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1.Text);
Note:
You should not do it in the first place. You should consider using parameterized queries instead. So, what you should be doing is
SqlCommand cmd = new SqlCommand("SELECT * FROM Enroll WHERE ID=#ID");
cmd.Parameters.AddWithValue("#ID", textBox1.Text.Trim());
What about changing
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1);
to
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1.Text);
This will be more appropriate :
command.CommandText = ("SELECT * FROM Enroll WHERE ID=" + textBox1.text.toString()+"");
Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....