Really, you are sending at your dbms this query
SELECT ID FROM Student WHERE Name ='' divyesh ''
your dbms interprets correctly the sql up to
SELECT ID FROM Student WHERE Name =''
then it finds
divyesh ''
and it tries to know first if divyesh it is a column of Student table, since it isn't raise an error, that you see in the application exception..
To correct this error, you should double quoting your strings passed as filter at your dynamic querys in the app:
SELECT ID FROM Student WHERE Name =' "''+str+''" '
Generally, when coding a dynamic query, your case is being prevented, submitting the "str" filter parameter to a some helper method that check if some single quotes are present and eventually doubles them.
This is a (C#, or Java) trivial solution with respect to what said:
"SELECT ID FROM Student WHERE Name ='" + str.Replace("'", "''") + "' "
But I find that it is very difficult that in a database a "Name" field it is stored between single quotes, so I wonder what are you tring to do..
Anyway what you are doing, using single quote in the filter fields, it is also an element of sql-injection attacks..
You should avoid absolutely that sort of dynamic query, and use in your code some api based on an object model of a sql query statement with parameters, and so pass to the object that "contains" your query the input filters, instantiating parameter objects.
update after clarifications in the PO
String SName = null;
if(!string.IsNullOrEmpty(txtBox1.Text))
SName = txtBox1.Text.trim();
String sql="select id from student where name = @paramName";
SqlConnection connection = null;
SqlDataReader reader = null;
try
{
connection = GetConnection();
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter param = new SqlParameter("@paramName", SqlDbType.NVarChar, 50);
param.Value = SName ?? SqlString.Null;
command .Parameters.Add(param);
if (_sqltransection != null)
{
command.Transaction = _sqltransection;
}
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException ex)
{
throw new DBException(ex);
}
please note that the SqlDbType.NVarChar, 50 refers to the data type of your db field "Name" (that I suppose to be a varchar) and so it should be equal in tyope and lenght (for a "name" field should go well 50 chars), anyway, the lower the lenght of a parameter input filter is, better it is
SELECT ID FROM Student WHERE Name =divyesh