How efficient is it to reuse the command and connection object in ADO.net? - odp.net

There is a specific requirement where in I am required to connect to two different Oracle databases one after the other. Does it make sense to create new connection and command objects or should I reuse them like below? (Not sure if this would even work-just some pseudo code here)
OracleConnection conn = new OracleConnection(ConnectionString1);
OracleCommand cmd = new OracleCommand("StoredProcedure1 , conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.parameters.add("param1", OracleDbType.Varchar2 , 20 , ParameterDirection.Input);
conn.open();
cmd.ExecuteNonQuery();
conn.close();
// Second DB hit
conn.ConnectionString = ConnectionString2;
cmd.CommandText = "StoredProcedure1";
if (cmd.Parameters.Count > 0) cmd.Parameters.Clear();
cmd.parameters.add("param2", OracleDbType.Varchar2 , 30 , ParameterDirection.Input);
conn.open();
cmd.ExecuteNonQuery();
conn.close();
All criticism welcome.

Related

How to query SQL to RichEditControl DevExpress?

I want to fill data from SQL Server to RichEditControl.Text. I used this code but it doesn't work, my RichEditControl.Text has an empty string.
string connectionstring = "Data Source=ADMIN;Initial Catalog=Shoplacviet;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionstring);
conn.Open();
string query = "select * from so";
SqlCommand cmd = new SqlCommand(query, conn);
var reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
richEditControl1.Options.MailMerge.DataSource = dt;
richEditControl1.Options.MailMerge.ViewMergedData = true;
richEditControl1.Text = dt.ToString();
conn.Close();

ExecuteNonQuery returning a 0?

I have the following code that is comparing a hash value and username to the corresponding hash value and username in a local database (App_Users3)
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT Username, Hash FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
// savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value = savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show(" Query successful.. something matched.. ");
// change page.. load a profile?
}
It doesn't throw any errors but I don't understand why the messagebox isn't showing up.
ExecuteNonQuery returns the rows affected by modifying data statements (insert, update, delete). You should use ExecuteScalar for such select statements, and for example return the user's ID value. If you want to return more than one value (either multiple rows or multiple columns), you should use ExecuteReader.
Here is your code modified to return UserID of the matched user.
//-
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
var cmd = new SqlCommand(#"SELECT UserId FROM App_Users3 WHERE Hash = #Hash AND Username = #Username");
cmd.Connection = con;
//savedPasswordHash = cmd.ExecuteScalar() as string;
cmd.Parameters.Add("#Hash", SqlDbType.NVarChar, 50).Value= savedPasswordHash;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 400).Value = AppUsername;
if (cmd.ExecuteScalar() != null) {
MessageBox.Show(" Query successful..something matched.. ");
//change page.. load a profile?
}
}

"Incorrect syntax near ')'."

I have a program that is to take a couple inputs and do stuff to them then store them in a local database (using SQL Server).
I have the following code for the connection:
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
String st = "INSERT INTO data(Username,Password, Hash, EncryptedPassword)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
cmd.ExecuteNonQuery();
con.Close();
It fails at the cmd.ExecuteNonQuery(); line, and throws this exception :
Incorrect syntax near ')'
I'm not even really sure where to start, as I haven't done any of this since college (107 years ago). Can anybody help me get started? I've been scouring but nothing seems to be working.
Maybe your insert should look like this:
INSERT INTO data (Username, Password, Hash, EncryptedPassword)
VALUES (#Username, #Password, #Hash, #EncryptedPassword)
The VALUES clause will need to be within the insert statement string. I would also recommend a using block instead of directly opening the SqlConnection, as will automatically close the connection upon exit whether by completion or error. While technically there isn't a difference between using String and string as in your command text, String would most often be used to reference a class while string is typically used in object references such as the case here.
string connectionString = #"YourConnectionString";
string st = "INSERT INTO data(Username,Password, Hash, EncryptedPassword) VALUES (#Username, #Password, #Hash, #EncryptedPassword)";
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(st1, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
con.Open();
cmd.ExecuteNonQuery();
}

Unable to convert object of type 'System.Data.SqlClient.SqlDataReader' to type 'System.IConvertible'

I am facing this error while i was trying to convert the session object type to int, I need to use that value in another query which is of datatype int.
SqlConnection sqlConnection1 = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=DESKTOP-59SGH72\\SQLEXPRESS;Trusted_Connection=True;Database=sport");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "select user_id from users where user_name='" + Session["usern"] + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
Session["userid"] = reader;
var uid = Convert.ToInt16(Session["userid"]);
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Please help me with this error !!
first of all your code is terrible -- it is totally going to get hacked by an injection attack. You should be using a parameterized query.
as to your question, something like this would work but you really should be doing lots of error checking and sanity checks:
reader = cmd.ExecuteReader();
reader.Read();
Session["userid"] = reader[0];
You probably should have looked at the documentation which has some nice examples
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

Stored procedure in loop

for (int i = 0; i < purchaseListView.Items.Count; i++)
Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
SqlCommand cmdFifo = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
cmdFifo.Connection = con.DataBaseConnection;
cmdFifo.CommandType = CommandType.StoredProcedure;
cmdFifo.CommandText = "insertInToMain";
This is my code and I want to know if the loop affects performance of my software and if this is the right way to call stored procedure in loop.
I have stored the procedure in a class and I want to call it from a form when the save button is clicked and insert 10 items in the database via same stored procedure.
Well, you are opening 10 connections, and it seems that you are not closing them, so you may run out of connections, but im guessing that's not the whole code, could you post the entire for ?
I would suggest you to create a table and insert the whole data into it by iterating through all the inputs ie., try to create a single stored procedure.
Running a for loop multpile times is inefficient and also the database will generate the result set number of times which will affect your performance as well due to network overhead.
You are creating a new connection object for every item which is highly inefficient.
Create one connection object and execute the stored procedure n times with the product details. Alternatively create a stored procedure to accept 10 items and insert the data at that level.
Move this outside the loop (You can access con and cmd inside the loop without creating a new instance:
Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
Inside your loop, you can add all the parameters to the cmd object.
cmd.Parameters.Add("#Item", SqlDbType.Int);
cmd.Parameters["#Item"].Value = purchaseListView.Items[i];
cmd.ExecuteNonQuery();
You should set up your connection and stored procedure before the loop and only update command parameter values and exec within the loop. Like this:
Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
SqlCommand cmdFifo = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
cmd.Parameters.Add("#Item", SqlDbType.Int);
cmdFifo.Connection = con.DataBaseConnection;
cmdFifo.CommandType = CommandType.StoredProcedure;
cmdFifo.CommandText = "insertInToMain";
//now that your connections & commands are set up, you can reuse them within the loop
for (int i = 0; i < purchaseListView.Items.Count; i++)
{
//ToDo:assign any SP parameter values
cmd.Parameters["#Item"].Value = purchaseListView.Items[i];
// ...
//then exec within the loop
cmd.ExecuteNonQuery();
cmdFifo.ExecuteNonQuery();
}