Is the database connection in this class "reusable"? - c#

I'm new to asp.net so this might be really basic question, but i cant figure it out.
I found a bit of code on the internet, that connects to database. And i created a namespace and some classes to use the same code in different projects.
The code and my class is the following:
namespace databaseFunctions
{
public class databaseConnection
{
private static string databaseConnectionString()
{
return "DRIVER={MySQL ODBC 5.1 Driver}; ........";
}
public static DataTable getFromDatabase(string SQL)
{
DataTable rt = new DataTable();
DataSet ds = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(databaseConnectionString());
OdbcCommand cmd = new OdbcCommand(SQL, con);
da.SelectCommand = cmd;
da.Fill(ds);
try
{
rt = ds.Tables[0];
}
catch
{
rt = null;
}
return rt;
}
public static Boolean insertIntoDatabase(string SQL)
{
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(databaseConnectionString());
OdbcCommand cmd = new OdbcCommand(SQL, con);
con.Open();
try
{
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
}
}
There is no problem getting data from database, or insert data into some database.
But. when i try to get the last_insert_id() from the mysql database. i only get a zero.
This is why i think that this piece of code I've created and copied from internet, creates a new connection for every time i call the "getFromDatabase(SQL)"
Is there anyone that could help me with fixing this class getFromDatabase() to keep the databaseconnection alive until i tell the program to abandon the connection?
I guess it is the "new OdbcConnection" that should be changed? Is it possible to check if there already is a connection alive?
I've done this hundreds of times in classic asp, but now, with classes and stuff. I'm totally lost.

The problem you face is that you've coded yourself into a "new connection per action" corner. What you really want to aim for,and is considered best practice, is "new connection per batch of actions".
What I recommend in this case is to open connection when required, and close when disposed. What we'll do is move the odbc adapters to a larger scoped variable so that it can be accessed within the class.
namespace databaseFunctions
{
public class databaseConnection:IDisposable
{
private OdbcConnection con;
private string connectionString;
public databaseConnection(string connectionString){
this.connectionString = connectionString;
}
public void OpenConnection(){
if (con == null || con.IsClosed ){ // we make sure we're only opening connection once.
con = new OdbcConnection(this.connectionString);
}
}
public void CloseConnection(){
if (con != null && con.IsOpen){ // I'm making stuff up here
con.Close();
}
}
public DataTable getFromDatabase(string SQL)
{
OpenConnection();
DataTable rt = new DataTable();
DataSet ds = new DataSet();
OdbcCommand cmd = new OdbcCommand(SQL, con);
da.SelectCommand = cmd;
da.Fill(ds);
try
{
rt = ds.Tables[0];
}
catch
{
rt = null;
}
return rt;
}
public Boolean insertIntoDatabase(string SQL)
{
OpenConnection();
OdbcCommand cmd = new OdbcCommand(SQL, con);
con.Open();
try
{
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
}
// Implementing IDisposable method
public void Dispose(){
CloseConenction();
}
}
}
Now the next time you use your class do something like
using (DatabaseConnection db = new DatabaseConnection()){
db.InsertIntoDatabase(...);
db.GetLastInsertID();
db.GetFromDatabase(...);
}
At the end of that code block, because it is IDisposeable, it will close that connection for you in the dispose method.
Things I changed:
implemented IDisposable interface
changed methods from static to class methods.
added new methods for opening closing connection
moved connection variable to class level scope
added an argument to the constructor that lets you pass in a connection string (you should put this connection string in you Web.Config
Edits:
constructor takes in connectionString per suggestion.

Yes, the code you posted is creating a new database connection every time a method is called, but that's not a problem. The problem is that it is not disposing the connection properly. The way to handle something like this is as follows:
using (OdbcConnection con = new OdbcConnection("yourconnectionsstring"))
{
con.open();
OdbcCommand command = new OdbcCommand("command_text",con);
command.ExecuteQuery(); //or what ever you need to do
}
That way the connection is being disposed properly since using is just syntactic sugar for try/finally
What you need to do is execute the 2 sql statements in the same transaction in a way that you insert the record in the first sql statement and retrieve the last inserted id on the next insert before ending the transaction. For example:
using (OdbcConnection con = new OdbcConnection("yourconnectionsstring"))
{
con.open();
OdbcTransaction tran = con.BeginTransaction()
OdbcCommand command = new OdbcCommand("first_sql_statement_here",con);
command.ExecuteNonQuery();
command.CommandText = "select last_insert_id();";
int result =command.ExecuteScalar();
tran.commit();
}
That is pretty much the idea.

You should let the connection pool handle your connections; That means you Close() every connection as soon as possible, and only create a new one at the last possible moment.
So yes - keep creating new ones for separate transactions.

Related

Handling Database Connection in C#

I am Creating WinForm application using C# and SqlServer. I have to handle many database CRUD Queries on it. And also there are so many forms and so many controllers.
Now I want to know is, If i create common class for handle database connectivity with many methods for open connection, close connection, execute Sql command or do any other data retrievals. This method is good or bad?
or below method for run every query is good or bad?
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=MYDB"))
{
connection.Open();
// Pool A is created.
}
which method is better for performance and security?
Here are some points to think about when using a connection.
1) Dispose the connection object as soon as you no longer need it by using the using statement:
using (var conn = new SqlConnection(connectionstring))
{
// your sql magic goes here
}
2) If you're not disposing the object immediately, you can make sure the connection is closed using a try-finally statement:
var conn = new SqlConnection(connectionstring);
try
{
// do sql shizzle
}
finally
{
conn.Close();
}
3) To prevent SQL injection, use parameterized queries, never concatenated strings
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using(var comm = new SqlCommand("select * from FooBar where foo = #foo", conn))
{
comm.Parameters.Add(new SqlParameter("#foo", "bar"));
// also possible:
// comm.Parameters.AddWithValue("#foo", "bar");
using(var reader = comm.ExecuteReader())
{
// Do stuff with the reader;
}
}
}
4) If you're performing multiple update, insert or delete statements, and they all need to be succesful at once, use a transaction:
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using(var trans = conn.BeginTransaction())
{
try
{
using(var comm = new SqlCommand("delete from FooBar where fooId = #foo", conn, trans))
{
comm.Parameters.Add(new SqlParameter { ParameterName = "#foo", DbType = System.Data.DbType.Int32 });
for(int i = 0; i < 10 ; i++)
{
comm.Parameters["#foo"].Value = i;
comm.ExecuteNonQuery();
}
}
trans.Commit();
}
catch (Exception exe)
{
trans.Rollback();
// do some logging
}
}
}
5) Stored procedures are used similarly:
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using (var comm = new SqlCommand("FooBarProcedure", conn) { CommandType = CommandType.StoredProcedure })
{
comm.Parameters.Add(new SqlParameter("#FooBar", "shizzle"));
comm.ExecuteNonQuery();
}
}
(Source stored procedures: this Answer)
Multi threading: The safest way to use multi threading and SQL connections is to always close and dispose your connection object. It's the behavior the SqlConnection was designed for. (Source: Answer John Skeet)
Best practice is make a common DBHelper class and create CRUD methods into that class.
I am adding code snippet.This may help you.
web.config
<connectionStrings>
<add name="mssqltips"
connectionString="data source=localhost;initial catalog=mssqltips;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
DBHelper.cs
//Opening Connection
public SqlConnection GetConnection(string connectionName)
{
string cnstr = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
SqlConnection cn = new SqlConnection(cnstr);
cn.Open();
return cn;
}
//for select
public DataSet ExecuteQuery(
string connectionName,
string storedProcName,
Dictionary<string, sqlparameter=""> procParameters
)
{
DataSet ds = new DataSet();
using(SqlConnection cn = GetConnection(connectionName))
{
using(SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
// assign parameters passed in to the command
foreach (var procParameter in procParameters)
{
cmd.Parameters.Add(procParameter.Value);
}
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
}
//for insert,update,delete
public int ExecuteCommand(
string connectionName,
string storedProcName,
Dictionary<string, SqlParameter> procParameters
)
{
int rc;
using (SqlConnection cn = GetConnection(connectionName))
{
// create a SQL command to execute the stored procedure
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
// assign parameters passed in to the command
foreach (var procParameter in procParameters)
{
cmd.Parameters.Add(procParameter.Value);
}
rc = cmd.ExecuteNonQuery();
}
}
return rc;
}
If you do not want to dispose context every time you can create repository class and inject SqlConnection inside.
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=MYDB"))
{
repository.SetConnection(connection);
var values = repository.GetSomething();
}
And Create Class:
public Class Repository
{
private SqlConnection _connection {get; set;}
public void SetConnection(SetConnection connection)
{
_connection = connection;
}
public string GetSomething()
{
_connection.Open();
//do stuff with _connection
_connection.Close();
}
}
Anyway I recommend you to read about ORM's (Entity Framework or Dapper) and SQL injection attack.

Is this the right order to clear SqlDataAdapter and Sql Command Parameters and close the connection?

I am new to SQL and C# , I am using windows forms C#.
As shown in the example code, is this the correct order of clearing SqlDataAdapter and clearing Sql Command Parameters and closing the connection?
Please guide me. Thank you
public partial class C1 : UserControl
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand = new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();
public C1()
{
InitializeComponent();
DataTable.Rows.Clear();
DataTable.Columns.Clear();
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM taqble1";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
buttonMD1_1.Text = Convert.ToString(DataTable.Rows[0]["Button_Text"]);
buttonMD1_2.Text = Convert.ToString(DataTable.Rows[1]["Button_Text"]);
buttonMD1_3.Text = Convert.ToString(DataTable.Rows[2]["Button_Text"]);
buttonMD1_4.Text = Convert.ToString(DataTable.Rows[3]["Button_Text"]);
// I did not clear DataTable because later I will use it
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
The order of distruction of your objects is not too important here, the important thing is to avoid global variables and be sure to always dispose the disposable objects
public C1()
{
InitializeComponent();
using(SqlConnection MyConnection = new SqlConnection(...))
using(SqlCommand MyCommand = new SqlCommand("SELECT * FROM taqble1", MyConnection))
using(SqlDataAdapter adapter = new SqlDataAdapter(MyCommand))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
.... button code ....
}
}
The Using Statement closes and dispose the disposable objects also in case of Exceptions. The DataTable object is local, so when the code exits (and you don't need it anymore) it will be automatically disposed.
Avoid keeping a global object for the connection, there is a Connection Pooling infrastructure that allows to get good performance in using this kind of object. The SqlCommand is lightweight and it is easily rebuilt when you need it, the SqlDataAdapter instead is meant to be reused for updating when you bind the DataTable to a grid, so sometimes is necessary to keep it global.
In your context, I think you should simply use a SqlDataReader instead of an SqlDataAdapter
public C1()
{
InitializeComponent();
using(SqlConnection MyConnection = new SqlConnection(...))
using(SqlCommand MyCommand = new SqlCommand("SELECT * FROM taqble1", MyConnection))
{
DataTable dt = new DataTable();
using(SqlDataReader reader = MyCommand.ExecuteReader())
{
dt.Load(reader);
.... button code ....
}
}
}
I see a lot of time this kind of error, in particular around the connection object. People thinks to get better performances keeping it global. That's not true and both your local and remote resources are stressed with a global connection object.

Do we need open db whendb is defined in using?

when I use using for connections, I know there is no need to use close or dispose. I wonder, do we need to use open?
using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
{
dbSqlConnection.Open(); // is this required?
}
Yes, you need to open it.
The using statement calls the Dispose method in a finally block. It doesn't open any connection. If your code inside in using statement doesn't open your connection on behind (like SqlDataAdapter), you need to open it manually.
using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
{
}
is equavalent to
var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"];
try
{
}
finally
{
if (dbSqlConnection != null)
((IDisposable)dbSqlConnection).Dispose();
}
As you can see, using statement doesn't do anything about opening a connection.
It depends on what you're doing...if you're manually executing a command using the SqlCommand object you will definitely need to open the connection before you execute any methods on the command. However, if you're using something like DataAdapter...you don't have to because it will manage the connection for you.
Using the SqlCommand object...
using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
{
var cmd = new SqlCommand("Your_Sql_Query", con);
dbSqlConnection.Open(); // is this required?
cmd.ExecuteNonQuery();
}
using a SqlDataAdapter...
using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, dbSqlConnection );
adapter.Fill(ds);
}
Notice that the SqlDataAdapter will manage the connection for you, it will open and dispose it
It depends on what you are doing. The SqlAdapter for example opens and closes the connection by itself.
If you use the SqlCommand then yes, you need to open the connection manually to use it
because the constructor of SqlConnection does not open the connection automatically.
As you said, the Dispose method (automatically called when leaving the using block) closes the connection if they is still open.
Using
using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
{
dbSqlConnection.Open(); // is this required?
}
Try finally
var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"];
try
{
SqlCommand command = new SqlCommand("SELECT ...", dbSqlConnection);
dbSqlConnection.Open();
// execute the SqlCommand e.g. ExecuteReader, ExecuteNonQuery, ExecuteScalar
}
catch (Exception ex)
{
// handle the exception
}
finally
{
// this gets called even if a exception has occured
if (dbSqlConnection != null)
dbSqlConnection.Dispose();
}
MSDN - SqlConnection Class
MSDN - SqlDataAdapter Class
MSDN - SqlCommand Class
MSDN - IDisposable Interface
MSDN - using Statement
no you do not need to do it always its depend on how you going to implement im not use open() command
here is the way to do it automatically with DataAdapter
SqlConnection con = dBClass.SqlConnection(); // return the connection string
SqlDataAdapter da = new SqlDataAdapter("[PR_R_TRN_test]", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#plong_ID", SqlDbType.BigInt).Value = ID;
DataSet result = new DataSet();
da.Fill(result);

Concurrecy In Static Classes

Can anyone please suggest me whether this code will cause concurrency or not.
This is a static class used in forms and and used for some database transactions.
This involves invoking of static function from asp.net pages and passing parameters as ref type.
I am using reference type.
As it is web based,does it Create some concurrency.
///
Here is code from my sample class.
public static class DataClass
{
static SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["sqlserverconnectionstring"]
.ConnectionString);
public static string GetCon()
{
return ConfigurationManager.ConnectionStrings["sqlserverconnectionstring"].ConnectionString;
}
public static void Conn(ref SqlConnection con)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
public static DataSet GetDataSet(string qry)
{
SqlDataAdapter adp = new SqlDataAdapter(qry, con);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
public static bool ExecuteCommand(ref SqlCommand cmd)
{
bool i =true;
cmd.Connection = con;
Conn(ref con);
SqlTransaction trans =con.BeginTransaction();
cmd.Transaction = trans;
try
{
cmd.ExecuteNonQuery();
trans.Commit();
}
catch
{
trans.Rollback();
i = false;
}
finally
{
cmd.Dispose();
con.Close();
}
return i;
}
}
Since you have defined a static SQLConnection, I believe it may cause concurrency issues.
static SqlConnection con = new SqlConnection (ConfigurationManager.ConnectionStrings["sqlserverconnectionstring"].ConnectionString);
If two different objects try to run a query, they will run them on the same instance of sql connection object.
Yes, that isn't thread-safe/ However, since SqlClient uses connection-pooling by default, you can just drop the static connection, and have each usage do something like:
using(var conn = OpenConnection()) {
...//code
}
where OpenConnection returns a new SqlConnection each time. This is not the same as a different underlying connection each time, and you will usually (in a winform) find a very low number of connections being used (1 if you get really lucky).

SellectCommad.connection Property not initialized

When i debug my application, it gives an error that SelectCommand.Connection Property is not been initialized. i dont know what am i doing here wrong :s. I actually want to add a filter over my search on the textchanged event of a textbox.
public class ConnectionClass
{
static SqlConnection cn;
public static SqlConnection Connection()
{
string myConnection = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
if (cn != null)
{
cn = new SqlConnection(myConnection);
cn.Open();
}
return cn;
}
}
public class ClassDataManagement
{
SqlConnection cn = ConnectionClass.Connection();
public DataTable GetData(string SQL)
{
SqlCommand cmd = new SqlCommand(SQL, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
protected void TextBoxFilterText_TextChanged(object sender, EventArgs e)
{
ClassDataManagement dm = new ClassDataManagement();
string query = "Select CourseCode from _Courses where coursecode like'%" + TextBoxFilterText.Text.TrimEnd() + "%'";
dm.GetData(query);
GridViewCourses.DataBind();
}
That's because your cn variable is null, and not getting initialized. Yet another example why it's a bad idea to initialize and open database connections in a static method.
Try this:
public class ClassDataManagement
{
public DataTable GetData(string SQL)
{
string YourConnectionString = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(YourConnectionString))
using (SqlCommand cmd = new SqlCommand(SQL, cn))
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
return dt;
}
}
With the SqlDataAdapter class, you don't need to explicitly call SqlConnection.Open(). The SqlDataAdapter.Fill() method handles all of the connection opening (and closing).
MSDN Reference on SqlDataAdapter.Fill()
As per the above reference, quoted:
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
Open connection and close as soon as possible.
public DataTable GetData(string commandString)
{
var result = new DataTable();
using (var cn = new SqlConnection(ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString))
using (var cmd = new SqlCommand(commandString, cn))
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(result);
}
return result;
}
Shouldn't that be
if (cn == null)
{
cn = new SqlConnection(myConnection);
cn.Open();
}
Although Sebastian's answer covers a good portion of what's wrong. Here is a more complete list.
You have SQL Injection issues. All queries should be parameterized otherwise you are asking for trouble. Especially when you are directly appending text entered by the user.
You are leaking resources: SqlConnection and SqlCommand. These need to be as close to the code that actually utilizes the connection and command as possible. Trust me, Windows is more than capable of handling all of the open/closing of connections through the build in connection pool. You don't need to maintain this yourself.
The code itself is brittle due to use of embedded SQL in your display layer. By way of example, let's say CourseCode is renamed to CourseId. You will have to search through and modify, potentially, a lot of code files just to make that change. There are multiple ways of limiting exposure to this issue; I'll leave that for you to research.
If I ran across this code in the wild, I would delete the ConnectionClass in its entirety. There is nothing that it is going to do for your that shouldn't be done elsewhere in a more robust manner.
Next I would delete the GetData() method. That is just bad code. You should never accept a full sql string and blindly execute it. There are a lot of security issues just in that one block of code.
Then I would rewrite the ClassDataManagement such that my SQL (if I really wanted it to stay embedded, which I wouldn't because I don't roll that way) was the container for all of my queries. I would have good methods like GetCourseByCourseCode(String courseCode) which would validate that the courseCode is in an expected format then pass it to my sqlcommand object as a parameter to the query.
For bonus points I'd expand on the above by looking at what calls could be better served by cached data. By having them in identified methods, it's much easier to pick and choose what can come from the cache vs what I really need to go across the network and run a query for.
Next, I would make sure that everywhere I made a SQL call, I had my SqlConnection, SqlCommand and readers wrapped in using clauses. It's the best way to ensure that everything is properly closed and disposed of prior to leaving the method. Anything less and you are inviting trouble.
Finally, I would highly consider using Enterprise Library for my data access. It's much better.
Having all given advices, to solve your current problem, you may try this way also:
public class ConnectionClass
{
static SqlConnection cn;
public static SqlConnection Connection()
{
string myConnection = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
return new SqlConnection(myConnection);
}
}
public class ClassDataManagement
{
public DataTable GetData(string SQL)
{
using (SqlConnection cn = ConnectionClass.Connection())
{
//SqlCommand cmd = new SqlCommand(SQL, cn);
SqlDataAdapter da = new SqlDataAdapter(SQL,cn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
......
public DataTable GetData()
{
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
string expression = "Parameter value";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name",
SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (SqlDataAdapter da = new SqlDataAdapter(SQL, cn))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}

Categories

Resources