Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my Search Button :

C#
private void btnSearch_Click(object sender, EventArgs e)
    {
        string RegNo = txtRegNo.Text;
        txtFname.Text = dba.ReturnStudentData("RegNo", "Student", RegNo, "PhoneNo");
        txtLname.Text = dba.ReturnStudentData("RegNo", "Student", RegNo, "Lname");
        txtPhoneNo.Text = dba.ReturnStudentData("RegNo", "Student", RegNo, "PhoneNo");

    }


This is my DB_Access :

C#
public string ReturnStudentData(string Primary_key, string Table_Name, string RegNo, string Column)
    {
        string temp = "";
        if (conn.State.ToString() == "Closed")
        {
            conn.Open();
        }
        SqlCommand newCmd = conn.CreateCommand();
        newCmd.CommandType = CommandType.Text;
        newCmd.CommandText = "SELECT" + Column + "FROM" + Table_Name + "WHERE" + Primary_key + "=" + RegNo + "";
        SqlDataReader dr = newCmd.ExecuteReader(); **// here i got error**

        while(dr.Read())
        {
            temp = dr[Column].ToString();
        }
        dr.Close();
        conn.Close();
        return temp;
    }
Posted
Updated 31-Oct-14 9:33am
v2

Spaces my friend, spaces...
Try this:
C#
newCmd.CommandText = "SELECT " + Column + " FROM " + Table_Name + " WHERE " + Primary_key + "=" + RegNo + "";

But you really should be trying to use parameterised queries, and validating your table and column names rather than concatenating strings, as that could leave you wide open to SQL injection - which can damage or destroy your database.

Personally, I wouldn't risk that code!
 
Share this answer
 
Comments
Member 11196678 31-Oct-14 15:56pm    
thanks dude for the help, I will correct my work again.
You are doing it wrong — your query is composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but there is way more important issue: it opens the doors to a well-known exploit called SQL injection.

This is how it works: http://xkcd.com/327[^].

What to do? Just read about this problem and the main remedy: parametrized statements: http://en.wikipedia.org/wiki/SQL_injection[^].

With ADO.NET, use this: http://msdn.microsoft.com/en-us/library/ff648339.aspx[^].

Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();[^],
hi name is not displaying in name?[^].

—SA
 
Share this answer
 
Comments
Maciej Los 31-Oct-14 16:45pm    
You're right, Sergey!
+5!
Sergey Alexandrovich Kryukov 31-Oct-14 19:08pm    
Thank you, Maciej.
—SA
Yeah, what Griff said.
Additionally, you should have used the debugger to show you the resultant CommandText -- the problem should have been obvious.
If it isn't obvious (and they aren't always), then you could have copied it and pasted it into SSMS and tried to execute it there.

I don't tink your technique of passing in the table, column, and key names are a good idea.
May I suggest that, if you insist on doing that, you use , params string[] Column) and pass in all the columns you want at once, rather than concatenating and hitting the database for each column?

Because you are returning at most one value, you may want to use ExecuteScalar rather than ExecuteReader.

But, as Griff said, you should validate the names. Because you seem to be using SQL Server, this can be as easy as querying the database catalogs.

Have a look at this, it ensures that the names passed into the method actually exist:

SQL
SELECT 'SELECT [' + D.name + '] FROM [' + A.name + '].[' + B.name + '] WHERE [' + C.name + '] = @key'
FROM sys.schemas A
INNER JOIN sys.objects B
ON A.schema_id=B.schema_id
INNER JOIN sys.columns C
ON B.Object_id=C.object_id
INNER JOIN sys.columns D
ON B.Object_id=D.object_id
WHERE A.name=@schemaname
AND B.name=@tablename AND B.type='U'
AND C.name=@keyname
AND D.name=@columnname


Use ExecuteScalar to execute something like that (with parameters). If the result is not DBNull.Value then you know the names were good and you can use the result as the CommandText.
 
Share this answer
 
Comments
Member 11196678 31-Oct-14 16:54pm    
I found the same problem again. what is wrong?


this is my update button =

private void btnUpdate_Click(object sender, EventArgs e)
{
dba.update_student(txtRegNo.Text, txtFname.Text, txtLname.Text, txtPhoneNo.Text);
MessageBox.Show("Data Succesfully Update");

}

This is my DB_Access =

public void update_student(string regNo, string fName, string Lname, string phoneNo)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "update Student set Fname = '" + fName + "',Lname = '" + Lname + "',Phone = '" + phoneNo + "'where regNo = '" + regNo + "' ";
newCmd.ExecuteNonQuery(); **// here i got error**
}
PIEBALDconsult 31-Oct-14 17:06pm    
Please use a parameterized query -- it eliminates all kinds of problems.
At last use the debugger to loko at the CommandText, and paste it into SSMS if you need to.
Please, read what Sergey wrote in his answer and read my comment.

Instead of this:
C#
newCmd.CommandText = "SELECT" + Column + "FROM" + Table_Name + "WHERE" + Primary_key + "=" + RegNo + "";

use parameterized queries or even better (if it's SQL database) stored procedures[^].

See MSDN documentation:
Walkthrough: Using Only Stored Procedures (C#)[^]
How to: Execute a Stored Procedure that Returns No Value[^]
How to: Execute a Stored Procedure that Returns Rows[^]

Finally, i need to warn you. I'm not a follower such of queries, becasue of SQL Injection[^]!

SQL Injection and how to avoid it[^]
Stop SQL Injection Attacks Before They Stop You[^]
How To: Protect From SQL Injection in ASP.NET[^]
 
Share this answer
 
v3
Comments
PIEBALDconsult 31-Oct-14 17:07pm    
I don't think that protects against SQL injection.
Maciej Los 31-Oct-14 17:14pm    
Don't understand... What exactly?
I wrote i do not recommend such of queries, because of sql injection. Do i wrote something wrong? Please, show me where i made mistake.
PIEBALDconsult 31-Oct-14 17:25pm    
Your stored procedure should protect against SQL injection, I thought that was the point of your solution, but it does not.
Maciej Los 31-Oct-14 17:38pm    
Yeah, that's the point of my solution. Thank you for pointing me that. Changed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900