简体   繁体   中英

SQL query execution difficulty

I am doing validation while add student from the application. If I run following query

SELECT ID FROM Student WHERE Name =' " '+str+' " '

It will generate following error:

Invalid column name 'str'.

And my application going to generate DBException.

How can I solve this problem?

Edit

String SName=txtBox1.Text;

String sql="select id from student where name = ' "+SName.Trim()+" ' ";

SqlConnection connection = null;
SqlDataReader reader = null;
try
{
    connection = GetConnection();
    SqlCommand command = new SqlCommand(sql, connection);
    if (_sqltransection != null)
    {
        command.Transaction = _sqltransection;
    }
    reader = command.ExecuteReader(CommandBehavior.CloseConnection);
}            
catch (SqlException ex)
{
    throw new DBException(ex);
}

Where txtBox.Text=" '+str+' "

SELECT ID FROM Student WHERE Name =' " '+'divyesh'+' " '

But have no sense...

Maybe you'll prefer something like:

SELECT ID FROM Student WHERE Name like '%divyesh%'

If you want to add single cuotes in the string:

SELECT '''hello'''

First, your resulting query is invalid since double quotation mark is used for database object names, not for string literals: "divyesh" is a column name, 'divyesh' is a string. You need the second one, so change double quotes to single ones.

Second, never ever use user input to construct an SQL-statement like that. If your user chooses a name "'; DROP DATABASE yourdb; SELECT '" , your database is gone. Read more on the topic 'SQL injection'.

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

I agree with previous answer. In this case you must use Prepared Statements . In this page you can find examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM