I'm trying to prevent SQL injections. Am I doing this right? (I'm using MS Access.) Should I still use sqlparameter?
OleDbParameter[] myparm = new OleDbParameter[2];
myparm[0] = new OleDbParameter("#UserID", UserName.Text);
myparm[1] = new OleDbParameter("#Password", encode);
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
Close!
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#UserID", UserName.Text);
cmd.Parameters.AddWithValue("#Password", encode);
The parameters are part of the command object and you use the Parameters.AddWithValue method to set the parameter values to what you have defined in the query string.
By the way, you should be using using statements to encapsulate some of your objects, here is what I typically do:
using (OleDbConnection conn = new OleDbConnection(_connStr))
using (OleDbCommand = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT ...";
cmd.Parameters.AddWithValue(...);
cmd.ExecuteReader();
//...
}
That way you don't have to worry about cleaning up resources if something goes wrong inside or closing the connection when you are done.
Related
I have a hard time figuring out what is wrong about my code. The purpose is to take data from a registering form in ASP to my user data columns in my SQL database.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin
values(#UserName,#Password)";
SqlConnection cnn = new SqlConnection(cmd);
SqlCommand cmd2 = new SqlCommand(cmd, cnn);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
You're using the connection string in the connection variable but the variable you're passing to SqlCommand is cnn which doesn't have a valid connection string associated with it.
I've cleaned up your code and made use of using block to ensure the correct manner of disposing the object. Please see below:
string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
string query = "insert into UserLogin values(#UserName, #Password)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd.Parameters.AddWithValue("#Password", PasswordBox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have two SqlConnection variable and assigning wrong one in the SqlCommand. The working code will be:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin values(#UserName, #Password)";
SqlCommand cmd2 = new SqlCommand(cmd, connection);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
My code gets to conn.Open and gives me "Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll"
Here is the block of code:
_timer.Stop();
string path = #"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open(); // Dies here
SqlDataReader rdr = cmd.ExecuteReader();
Order is missing ...first open connection then use sql command
_timer.Stop();
string path = #"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
conn.Open(); // sholud be here
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader rdr = cmd.ExecuteReader();
Besides your code is not formatted either..Format like this
string path = #"C:\testlog.log";
String connectionString = ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open(); // sholud be here
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
String RawImportEnabled = Convert.ToString(reader["RawImportEnabled"]);
//Do some thing
}
}
This has some benefits like debugging the connection string by putting a breakpoints ,Disposal of connection without worrying for using statements etc
_timer.Stop();
string path = #"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
conn.Open(); // Dies here again.
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
I am trying to connect to an oracle database using C#.
Here is my code:
OracleConnection conn = new OracleConnection(); // C#
conn.ConnectionString = oradb;
conn.Open();
string sql = " select department_name from departments where department_id = 10"; // C#
OracleCommand cmd = new OracleCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text; ///this is the line that gives the error
What is the proper way to set the command type? Thank you.
Using Store Procedure:
using (OracleConnection conn = new OracleConnection( oradb ))
{
conn.Open();
OracleCommand cmd = new OracleCommand("StoreProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
//specify command parameters
//and Direction
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//string s = reader.GetInt32(0) + ", " + reader.GetInt32(1);
}
}
}
CommandType.Text: (not mandatory to specify CommandType).
using (OracleConnection conn = new OracleConnection( oradb ))
{
string sql = #"SELECT department_name FROM departments
WHERE department_id = #department_id";
conn.Open();
OracleCommand cmd = new OracleCommand(sql, conn);
//specify command parameters
cmd.Parameters.Add(new OracleParameter("#department_id", 10));
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//string s = reader.GetString(0);
}
}
}
Make sure you toss each of these pieces in a using() statement, i.e.
using( OracleConnection conn = new OracleConnection( oradb ) )
{
conn.Open();
using( OracleCommand cmd = new OracleCommand( "sql here", conn ) )
{
//cmd.Execute(); cmd.ExecuteNonQuery();
}
}
I am trying to use MYSQL select query with c#.
Following query for searching "ID" is working fine:
conn = new MySqlConnection(cs);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "select * from catalog_product_entity where entity_id = ?Id";
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
cmd.Parameters.Add("?Id", SqlDbType.Text).Value = ProductList[i].ProductId.ToString();
adp.Fill(MagentoProduct);
Now, I want to search exact string value in table. I am using following code and its giving empty result:
My Code:
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand("select * from catalog_category_entity_varchar where value = #Value;", conn);
cmd.Parameters.AddWithValue("#Value", "Storybooks");
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
log.WriteEntry(r.GetString("value"));
}
This is the problem:
where value = '?cname'
That's specifying ?cname as the literal value you're searching for - when you actually just want the parameter. Remove the quotes and it should be fine:
where value = ?cname
(You should use using statements for the connection and command, mind you...)
You could try SQL Reader
c = new MySqlCommand("select * from catalog_product_entity where column_nam = #Value;", conn);
c.Parameters.AddWithValue("#Value", your string);
MySqlDataReader r = c.ExecuteReader();
and then use Reader methods like reader.GetString("column_name"), ....
We use oracle database connection and our class database access does not have a dispose or close. It interferes with something or performance of the application? I saw this example:
string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from departments";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
And I realized that it opens the connection and then kills her. This is correct? Is there any other better?
I'm leaving my connection open and then ends up being closed for a while. I think that's it. This so wrong?
Use the Using statement with disposable objects. In particular with any kind of connection and datareaders
string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from departments";
cmd.CommandType = CommandType.Text;
using(OracleDataReader dr = cmd.ExecuteReader())
{
dr.Read();
label1.Text = dr.GetString(0);
}
}
Here you could read about the Using statement and why it is important. Regarding the connection and readers, you should enclose the objects with the using statement to be sure that everything is properly closed and disposed when you exit from the using block ALSO in case of exceptions