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)
{
}
}
Related
I have a form that checks whether values are in a database before adding them. Each field is in a different table, and to keep everything clean, I have a checkExists method for each field. Is there a way to have a separate method that connects to the database, so that I don't have to connect in every field method?
I'd like to do something like this so that my code is less messy:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
But I get a
local variable set_conn
Argument 2: Cannot Convert from Class_DB to System.Data.SqlClient.SqlConnection
I understand the error, so what can I do to return the correct value, or do I have to establish a connection within my CheckData_Comany() method?
Your method SetConnection should be returning SqlConnection back like:
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
and then you can have something like:
SqlConnection connection = set_conn.SetConnection();
and then pass it in SqlCommand constructor as parameter :
SqlCommand check_Company = new SqlCommand(query_string, connection);
Your complete method implementation would become :
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = #companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("#CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
and important thing to note is do not forget the close the connection finally by calling connection.Close(), otherwise it might cause eating up the resources that shouldn't happen when we are done with querying the database and we should release the resources occupied.
I'm using the following code in C# to connect to my SQL Server which works fine. But I would like to display a message to the user saying that if the connection was either successful or not and don't know how to do that. Could anyone help me?
This is my code:
string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";
private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
}
}
catch (Exception er) {
MessageBox.Show(er.Message);
}
}
You provided the answer yourself. Try the following code:
string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";
private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
MessageBox.Show("Connection successful !!");
}
}
catch (Exception er) {
MessageBox.Show("Connection unsuccessful..");
}
}
I'm not sure exactly what you want and I'm not sure if you have any Control that you want to publish the message in, but a simple messagebox would be like this:
string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";
private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
MessageBox.Show("Yay! You're connected!");
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
We're looking for a hands-on way to create a database from a given connection string with minimum code possible (e.g., to include in LINQPad scripts or C# scriptlets).
Is there a one-liner or something similar to create a database from a connection string? Most preferably something like "Static.CreateDatabase("connection string").
I have created a static class Scripts which contains a static method CreateDatabase
// USE Class Like this
Scripts.CreateDatabase("Connectionstring")
//Class
static class Scripts
{
static bool CreateDatabase(string Connectionstr)
{
bool result =false;
SqlConnection Conn = new SqlConnection(Connectionstr); // pass connection string and user must have the permission to create a database,
string Query = "CREATE DATABASE Exampledatabase ";
SqlCommand Command = new SqlCommand(Query, Conn);
try
{
Conn .Open();
Command.ExecuteNonQuery();
result =true;
}
catch (System.Exception ex)
{
result =false;
}
finally
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
}
return result;
}
}
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
String sql = "CREATE DATABASE MyDatabase";
SqlCommand myCommand = new SqlCommand(sql, myConn);
try {
myConn.Open();
myCommand.ExecuteNonQuery();
// OK
} catch (System.Exception ex) {
// failed
} finally {
if (myConn.State == ConnectionState.Open) {
myConn.Close();
}
}
Download nuget add as a reference to LINQPad.
Then use comand:
void Main()
{
var database = new ProductivityTools.CreateSQLServerDatabase.Database("XXX", "Server=.\\SQL2019;Trusted_Connection=True;");
database.Create();
}
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
}
I got a problem. I stack!
Don't know if i need a new class for it!
i want a methode for closing the connection via a Button click.
I already created the constructor:
public string Server;
public string Username;
public string Pwd;
public string DB;
MySqlConnection conn;
string ConnString;
public DBVerb(string eServer, string eUsername, string ePwd, string eDB)
{
this.Server = eServer;
this.Username = eUsername;
this.Pwd = ePwd;
this.DB = eDB;
}
And this two methods:
public void Connect(System.Windows.Forms.Label lblStatus)
{
try
{
ConnString = String.Format("server={0};user id={1}; password={2}; database={3}; pooling=false",
this.Server, this.Username, this.Pwd, this.DB);
conn = new MySqlConnection();
conn.ConnectionString = ConnString;
if (conn != null)
conn.Close();
conn.Open();
if (conn.State == ConnectionState.Open)
{
lblStatus.Text = String.Format("Verbindung zu {0} user: {1} Zeit: {2}", this.Server, this.Username, DateTime.Now.ToString());
}
else
{
MessageBox.Show("Felher");
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Fehler:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void ClConnect()
{
conn = new MySqlConnection();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
Here I'm calling the Methode:
private void cmdHerstellen_Click(object sender, EventArgs e)
{
string lServer = txtBServ.Text;
string lUID = txtBUid.Text;
string lPawd = txtBPass.Text;
string lDB = txtBDat.Text;
DBVerb VerbindungHerstellen = new DBVerb(lServer, lUID, lPawd, lDB);
VerbindungHerstellen.Err();
VerbindungHerstellen.Connect(lblStatus);
}
private void cmdAbbr_Click(object sender, EventArgs e)
{
}
If i call the Method ClConnect() than I have to give the arguments for the parameter, but I already did, so it don't work.
Any idea how to do it?
You are storing your dbconnection as a field in your class. When you want to close it you don't want to assign a new connection object to it with conn = new MySqlConnection(); and instead just want to remove that line and replace it with a check to see if conn is null or not. If its null then no work needs to be done (or maybe its an error) and if its not null then you can check if it is open and close if appropriate.
You probably also want to be careful of where you are creating new objects in the connect method. If conn already exists you probably don't want to (or need to) create a new connection object.
My last comment is that there is something wrong sounding about the user needing to click a button to close your connection. That should be soemthign the code worries about and not the user. However, I obviously don't know what you are doing with this so I can't say it is definitely wrong, just that it feels a bit wrong. :)