C# .NET - Prevent / Avoid SQL Injection Attack while retrieving data from MS Access file

Asked By Aldo Liaks on 26-Feb-09 07:33 AM
 Hi guys,

I need to retrieve data from MS Access file (.mdb) using C# code.

I have to insert in the sql string, a value retrieved from a text box.

How do I prevent / avoid a SQL Injection attack?

I thougth I can use the code below, but it's not working...

// Create new SQLCommand.  
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand();  
 
// Set SQLCommand to Text type.  
sqlCommand.CommandType = CommandType.Text;  
 
// Get the SQL String.  
sqlCommand.CommandText = "SELECT * FROM Table1 WHERE Column1 = 'myUser'";  
// Insert the value from the text box into the string as parameterized value.  
sqlCommand.Parameters.AddWithValue("myUser", myUser.Text);  
 

Any help will be appreciated,
Aldo.

Install URL Scanner in IIS

Sat Sat replied to Aldo Liaks on 26-Feb-09 08:29 AM

You need install URL Scanner in IIS. It can be available from web platform installer

http://www.microsoft.com/web/channel/products/WebPlatformInstaller.aspx

refer http://www.connectionstrings.com for connections

You should be using the OleDb namespace instead of SqlClient

Robbe Morris replied to Aldo Liaks on 26-Feb-09 08:33 AM
System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand();  
 
// Set SQLCommand to Text type.  
sqlCommand.CommandType = CommandType.Text;  
 
// Get the SQL String.  
sqlCommand.CommandText = "SELECT * FROM Table1 WHERE Column1 = @myUser";  
// Insert the value from the text box into the string as parameterized value.  
sqlCommand.Parameters.AddWithValue("myUser", myUser.Text);

SOLVED!!

Aldo Liaks replied to Robbe Morris on 26-Feb-09 08:44 AM

You are right, the code below is working for me:

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connString + dataSource);

System.Data.OleDb.OleDbCommand oleDbCommand = new System.Data.OleDb.OleDbCommand("SELECT * FROM Table1 WHERE Column1 = @myUser");

oleDbCommand.CommandType = CommandType.Text;

oleDbCommand.Parameters.AddWithValue("@myUser", txtUserName.Text);

oleDbCommand.Connection = conn;

System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(oleDbCommand);

DataSet ds = new DataSet();

da.Fill(ds, tableName);

Microsoft Access ADO.NET Code Generator
Robbe Morris replied to Aldo Liaks on 26-Feb-09 09:55 AM

If you are using stored queries in access.  You may find the source code to this old utility I wrote quite helpful.

http://www.eggheadcafe.com/articles/microsoftaccess_source_code_generator.asp

Just SELECT...
Aldo Liaks replied to Robbe Morris on 26-Feb-09 10:01 AM

Hi Robbe,

I am not using stored queries, just something like:

SELECT @colName FROM Users

@colName will be i.e. UserName, or UserPassword...

Thanks

Wrong Post!
Aldo Liaks replied to Aldo Liaks on 26-Feb-09 10:01 AM
Sorry, this is another post!