SqlConnection by Method - c#

I'm trying to implement a method that will provide the SqlConnection, how should I do it?
public class DAL
{
public bool dbCon()
{
string comboValue;
try
{
using (SqlConnection sqlConn =
new SqlConnection(#"Data Source =VirtualXP-64805;Initial Catalog=CTS_Demo;Integrated Security=SSPI"))
{
sqlConn.Open();
}
}
catch (SqlException Ex)
{
MessageBox.Show(Ex.ToString());
}
}
}

You method should return the connection object not a bool value, or you may define a class level connection variable and use that.
But When it comes to Database Connection then open it as late as possible and close it as early as possible
Instead of opening the connection from the method you may simply return the connection object and open it where you need it. Something like:
public SqlConnection dbCon()
{
return new SqlConnection(#"Data Source =VirtualXP-64805;Initial Catalog=CTS_Demo;Integrated Security=SSPI");
}
and then where you are using it:
using(SqlConnection conn = dbCon())
{
conn.Open();
.... your code
}
Or you can get rid of the method and simply call the new SqlConnection with connection string from the configuration.
EDIT:
Since you want to return an open connection from your method, you can do the following, but IMO its not the recommended way, you have to call Dispose manually for each connection object, since you will not use it within using statement.
public SqlConnection dbCon()
{
SqlConnection sqlConn;
try
{
sqlConn = new SqlConnection(#"Data Source =VirtualXP-64805;Initial Catalog=CTS_Demo;Integrated Security=SSPI")
}
catch(SqlException)
{
//your exception handling details
sqlConn = null;
}
return sqlConn;
}

Related

C# method returns connect to different databases

UPD:
I have a static class for work with database.
This class contains the method which returns connect to database. Early this method returns connect to Advantage database (AdsConnection):
static private AdsConnection GetConnection(){
var conn = new AdsConnection();
conn.ConnectionString = here my connection string
return conn;
}
Now, I need to change this method. I need that this method returns connect to different databases types (Advantage database, Oracle database).
The method will work into public methods in my class. For example, method for get data from any table from database.
public static List<entity1> GetEntities(){}
Into this method the first of my step is to resolve the type of database, then connect to database. Then get data from database and the last step is return data (List< entity1 >).
In the step to connect the database I need to use the method GetConnection("Ads")
This method returns current connect to database and then I can use this connect for work
I changed method:
My first version
static private T GetConnection<T>(string dbType)
{
if (dbType.Equals("Oracle"))
{
OdbcConnection conn = new OdbcConnection
conn.ConnectionString = here my connection string
return (T)conn;
}
if (dbType.Equals("Ads"))
{
AdsConnection conn = new AdsConnection
conn.ConnectionString = here my connection string
return (T)conn;
}
return default(T);
}
But, my solution does not work. I have errors:
Cannot convert type 'System.Data.Odbc.OdbcConnection' to 'T'
Cannot convert type 'Advantage.Data.Provider.AdsConnection' to 'T'
I do not know how to resolve my problem.
Please, tell me how to resolve my problem?
Now, I use the following code (this solution give me #khlr):
static private IDbConnection GetConnection(string dbType)
{
if (dbType.Equals("Oracle"))
{
OdbcConnection conn = new OdbcConnection
conn.ConnectionString = here my connection string
return conn;
}
if (dbType.Equals("Ads"))
{
AdsConnection conn = new AdsConnection
conn.ConnectionString = here my connection string
return conn;
}
return null;
}
Thank.
One way you can abstract the connection instantiation is by using DbProviderFactory of ADO.Net. You can basically pass it a provider name and it will give a connection based on the provider. This basically reduce the check of dbtype etc for you and I think its sensible approach when you need to target multiple database. Some of the code snippet are copied from MSDN.
In you config file you can multiple connection string set up with different database type and provider.
<configuration>
<add name="NorthwindAccess"
providerName="System.Data.OleDb"
connectionString=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Northwind.mdb;"
/>
Then in you method you can do following:
static DbConnection CreateDbConnection(
string providerName, string connectionString)
{
// Assume failure.
DbConnection connection = null;
// Create the DbProviderFactory and DbConnection.
if (connectionString != null)
{
try
{
DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);
connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
}
catch (Exception ex)
{
// Set the connection to null if it was created.
if (connection != null)
{
connection = null;
}
Console.WriteLine(ex.Message);
}
}
// Return the connection.
return connection;
}
You could do the following, since both connections inherit from IDbConnection:
static private IDbConnection GetConnection(string dbType)
{
if (dbType.Equals("Oracle"))
{
OdbcConnection conn = new OdbcConnection
conn.ConnectionString = here my connection string
return conn;
}
if (dbType.Equals("Ads"))
{
AdsConnection conn = new AdsConnection
conn.ConnectionString = here my connection string
return conn;
}
return null;
}

SQL Server : reconnect after lost connection

I want open WPF program, then SQL Server database is off and when database is back online, WPF should auto connect to the database. If I restart SQL Server, keep alive program and try connect to database until connection is available. Should I catch the exception and then repeat something?
I try restart application then I got exception, but anyway my program crash and stop working.
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch (SqlException ex)
{
//how stop crash? //
//System.Windows.Forms.Application.Restart();
return ex.ToString();
}
finally
{
connection.Close();
}
}
The thing to do is to centralize the creation of connections in a single static method for your entire application.
public static SqlConnection getConnection()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["quality"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}
In your code,every time you use a connection try this :
public int test()
{
SqlConnection conn = null;
try
{
try
{
conn = StaticContext.getConnection();
conn.Open();
//TODO OPERATION
}
catch (Exception e)
{
//return ex.ToString();
return -1;//MY_ERROR_CODE;
}
}
finally
{
conn.Close();
}
return 1//MY_SUCCES_CODE;
}
When you call DB method manage so the error:
if (test() == -1)
{
//MESSAGE BOX ERROR OR OTHER
}

DB connection made in using statement

In here it shows the error,some invalid argument
MyCode
static SqlConnection conDB = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
[WebMethod, ScriptMethod]
public static List<HomeImageSliders> GetHomeImageSliders()
{
List<HomeImageSliders> HomeImageList = new List<HomeImageSliders>();
try
{
using (SqlConnection con = new SqlConnection(conDB)) //<-- In here it shows the error
{
}
This is because you made a static DB connection, and tried to use it in the using.
Here is how you can fix this:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString)) {
... // Your code goes here
}
Also remove the declaration of conDB - it is unnecessary.
SqlConnection does not have a constructor that takes another SqlConnection. Plus having a static SqlConnection is not a best practice. I suspect you want:
// make the _connection string_ static, not the _connection_
static string conDB = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
[WebMethod, ScriptMethod]
public static List<HomeImageSliders> GetHomeImageSliders()
{
List<HomeImageSliders> HomeImageList = new List<HomeImageSliders>();
try
{
using (SqlConnection con = new SqlConnection(conDB)) error
{
}
SqlConnection constructor accepts connection string, but not another SqlConnection.

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'OracleConnection' Reuse of OracleConnection object

I would to reuse a OracleConnection object for more queries
so I wrote a simple class:
public static class DbConnectionsManager
{
/// <summary>
///
/// </summary>
private static OracleConnection _dbConnection = null;
/// <summary>
///
/// </summary>
/// <param name="aConnectionString"></param>
/// <returns></returns>
public static OracleConnection GetDatabaseConnection(string aConnectionString)
{
try
{
if (_dbConnection == null)
{
_dbConnection = new OracleConnection(aConnectionString);
_dbConnection.Open();
return _dbConnection;
}
if (_dbConnection.State == System.Data.ConnectionState.Closed)
{
_dbConnection.ConnectionString = aConnectionString;
_dbConnection.Open();
return _dbConnection;
}
if (!_dbConnection.ConnectionString.Equals(aConnectionString))
{
_dbConnection.Close();
_dbConnection.ConnectionString = aConnectionString;
_dbConnection.Open();
return _dbConnection;
}
return null;
}
catch (Exception e)
{
return null;
}
}
}
in this way I can use the connection several times:
using (OracleConnection connection =
DbConnectionsManager.GetDatabaseConnection(aDbConnectionString))
{
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM MYTABLE";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["EXAMPLE"];
Console.WriteLine(myField);
}
}
When I call the method the first time everything works fine.
If I recall the method the static object is != null but the connection result closed!
I never close the connection!
When you try to reopen the connection I have this exception
....
if (_dbConnection.State == System.Data.ConnectionState.Closed)
{
_dbConnection.ConnectionString = aConnectionString;
_dbConnection.Open();
return _dbConnection;
}
...
Error
Message = "Cannot access a disposed object.\r\nObject name: 'OracleConnection'."
As the error says it's a disposed object. That means you need to remove the using ( clause; this clause disposed your connection object and that's why you cannot use this object outside using (. That means you need to create a new object of class if you want to use it outside using (.
See: C# Using Statement
As the other answer explains, the using clause isn't a natural fit for something you're wanting to re-use. However I had the same idea - I would still like to use this type of pattern to auto-open & auto-close the connection. If that is what you were hoping to do, then the key is that the object you are "using" cannot be the OracleConnection itself since you do want to reuse this, and "using" it will kill it. You really just want a new object which opens the connection on creation, and closes the connection on Dispose, and nothing more. This should do the trick (I am using it for my own purposes):
internal class OpenedContext : IDisposable
{
private OracleConnection _connection;
public OpenedContext(OracleConnection conn) {
_connection = conn;
if (_connection.State != System.Data.ConnectionState.Open) _connection.Open();
}
public void Dispose() {
if (_connection.State != System.Data.ConnectionState.Closed) _connection.Close();
}
}
And then in your example you could do something like...
// Early on...
OracleConnection _connection = DbConnectionsManager.GetDatabaseConnection(aDbConnectionString);
// ... Later on, in various other calls ...
using (new OpenedContext(_connection))
{
OracleCommand command = _connection.CreateCommand();
string sql = "SELECT * FROM MYTABLE";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["EXAMPLE"];
Console.WriteLine(myField);
}
}
Although it's goofy in a way, I definitely prefer setting up a pattern like this to always expecting future coders to manually "wrap" the re-open & re-close around every database call. It's more readable (or ignorable) and less risky (if you're greatly concerned about leaving the connection closed while idle).
public OracleConnection GetConnection()
{
//Romove using(...) clouse
using (OracleConnection conn = new OracleConnection(_connSettings.GetConnectionString()))
{return con;}
The issue is inner using() clause problem.
using (OracleConnection con = GetConnection()){}

close opened connection using c#

Am using the below code in a class file and access this function for open the connection it return true. I want to close this connection state .I can't do this. please help me to do this.
common.cs
=========
public static bool DBConnectionStatus()
{
try
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_gym.mdb; Jet OLEDB:Database Password=gym_admin";
using (OleDbConnection conn = new OleDbConnection(conString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
}
catch (OleDbException)
{
return false;
}
catch (Exception)
{
return false;
}
}
protected void btn_general_Click(object sender, EventArgs e)
{
try
{
bool state = common.DBConnectionStatus();
if(state == true)
{
// Some operation
}
// I want to close this connection
}
catch (Exception e1)
{
}
}
A using statement is translated into three parts: acquisition, usage, and disposal.
using (OleDbConnection conn = new OleDbConnection(conString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
//connection is automatically closed and disposed here
}
More information at MSDN article.
You better give back an open connection because you need that in an OleDbCommand. You coukd hide the connection as well in the Common class if you like but if you keep it in the using statement there is no open connection when you get status so basically if true is returned your connection in reality is closed (and Disposed). Refactor to something like this:
public OleDbConnection GetOpenConnection()
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_gym.mdb; Jet OLEDB:Database Password=gym_admin";
OleDbConnection conn = new OleDbConnection(conString))
conn.Open();
return conn;
}
protected void btn_general_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection openConnection = common.GetOpenConnection())
{
// I want to close this connection
openConnection.Close(); // close asap
} // dispose
}
catch (Exception e1)
{
}
}

Categories