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
}
Related
I am using the Oracle Data Provider for .NET version 4.112.3.0 to access an Oracle 9 database from an ASP.NET web application. Even though I explicitly Close and Dispose of the OracleDataReader and OracleConnection objects, I receive an ORA-01000 maximum open cursors exceeded error at times.
Most of my ODP.NET code is wrapped into a custom class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Oracle.DataAccess.Client;
using System.Data;
namespace MyNamespace
{
public class MyOracleClass : IDisposable
{
private static string connectionString = "Data Source=myDB;Persist Security Info=True;User ID=myUser;Password=myPassword;";
private OracleConnection _conn;
private OracleTransaction _txn;
public MyOracleClass()
{
try
{
_conn = new OracleConnection(connectionString);
if (_conn.State != ConnectionState.Open)
_conn.Open();
_txn = _conn.BeginTransaction(IsolationLevel.ReadCommitted);
}
catch (Exception ex)
{
// Log Exception
throw ex;
}
}
public void Query(string query, ref OracleDataReader dr)
{
dr = null;
OracleCommand cmd = null;
try
{
if (_conn.State != ConnectionState.Open)
_conn.Open();
cmd = new OracleCommand(query, _conn);
dr = cmd.ExecuteReader();
}
catch (Exception ex)
{
// Log Exception
throw ex;
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
public void Disconnect()
{
try
{
if (IsConnectionOpen())
{
_txn.Rollback();
_conn.Close();
}
}
catch (Exception ex)
{
// Log Exception
}
}
public void Dispose()
{
Disconnect();
try
{
if (this._txn != null)
{
_txn.Dispose();
_txn = null;
}
}
catch (Exception ex)
{
// Log Exception
}
try
{
if (this._conn != null)
{
this._conn.Dispose();
}
}
catch (Exception ex)
{
// Log Exception
}
}
public bool IsConnectionOpen()
{
if (this._conn.State == ConnectionState.Open)
{
return true;
}
return false;
}
}
}
I then use the class in my program.
public void test()
{
OracleDataReader dr = null;
MyOracleClass oracleDb = null;
string query = "SELECT COL_1, COL_2, COL_3 FROM MY_TABLE";
try
{
oracleDb = new MyOracleClass();
oracleDb.Query(query, ref dr);
if(!dr.HasRows)
{
// No data found
}
else
{
while(dr.Read())
{
// Process data
}
}
}
catch(Exception ex)
{
// Log Exception
}
finally
{
if(dr != null)
{
dr.Close();
dr.Dispose();
}
oracleDb.Dispose();
}
}
My query returns an average of 500 rows. When I first experienced the issue, I decided to go to the database to see how many cursors were actually opening up. The OPEN_CURSORS parameter for my database is set to 100. For a given call to the query, I noticed there were 92 open cursors for this simple select query and would break the 100 cursor limit at times! Why would such a large number of cursors open when using the OracleDataReader?
Note, I've been testing this on a development system running Windows Server 2012 with IIS 8.0. I've also called the OracleConnection.ClearAllPools method once finished with the OracleConnection, but this didn't seem to help either. I also tested the query by populating a DataTable object by using the Fill method along with an OracleDataAdapter. Using this method only opened 3 cursors. Why is there such a variation in the number of cursors opened?
I have some Steam trading bots and i am trying to insert to a database whether a trade was successful or not (true). You can see my code below. I get absolutely no errors and the regular trades, functions and console logging works fine. I check the db for content and nothing is there.
I am new to SQL in C#. Is someone able to tell me whats wrong with my code?
public override void OnTradeAccept()
{
bool didSomething = false;
if ((Validate()) || (IsAdmin && mode == ADMINMODE) || ChooseDonate)
{
bool success = Trade.AcceptTrade();
if (success) //makes sure trades were successfull
{
//I removed con details
string constr = "server=;database=;userid=;password=;";
MySqlConnection con = null;
try
{
con = new MySqlConnection(constr);
con.Open(); //open the connection
string insertTrue = "INSERT INTO trade_success(state) VALUES ('true')";
MySqlCommand command = new MySqlCommand(insertTrue, con);
command.ExecuteNonQuery();
}
catch (MySqlException err) //We will capture and display any MySql errors that will occur
{
Console.WriteLine("Error: " + err.ToString());
}
finally
{
if (con != null)
{
con.Close();
}
}
Log.Success("Trade was successful!");
//sendChatMessage(tradeSuccessMessage1);
sendChatMessage(tradeSuccessMessage2);
Bot.SteamFriends.SetPersonaState(EPersonaState.LookingToTrade);
}
else
{
Log.Warn("Trade might have failed.");
Bot.SteamFriends.SetPersonaState(EPersonaState.LookingToTrade);
}
}
}
So i been trying to connect C# windows from to MYSQL database, i tryed many different methods that i found online but none seems to be working. here is my code please help (keep in mind this is the first time i use database before).
Here is the connecting class
class DbConnect
{
public static void DBConnect()
{
string connstr =
"server=localhost;user=root;database=login;port=3306;password=Password";
MySqlConnection conn = new MySqlConnection(connstr);
try
{
conn.Open();
}
catch
{
Console.WriteLine("went rong");
}
}
}
Here is the windows form im using
private void btnenter_Click(object sender, EventArgs e)
{
DbConnect.DBConnect();
MySqlCommand query = new MySqlCommand("INSERT INTO logininfo (username,
password) VALUES(#username, #password");
try
{
query.Parameters.AddWithValue("#username", txtusername.Text);
query.ExecuteNonQuery();
MessageBox.Show("S");
}
catch (Exception )
{
MessageBox.Show("something went wrong");
}
finally
{
DbConnect.DBClose();
}
}
User is passed in MySQL connection string using Uid. So your connection string should be like:
"server=localhost;Uid=root;database=login;port=3306;password=tro63jans";
You may see: MySQL connection string.
You should also catch exception in some object, so that you can get the details about the exception. Currently you are not showing any useful message from your exception.
catch (Exception ex) //at least
{
MessageBox.Show("something went wrong: " + ex.ToString());
}
One problem you have here is you're not setting the Connection property of your MysqlCommand to the MySqlConnection you're making earlier.
Change DBConnect() to return your MySqlConnection.
Set your MySqlCommand's Connection property to the returned value.
PSEUDO-CODE
MySqlConnection conn = DBConnect.DBConnect();
MySqlCommand command = new MySqlCommand(commandStr, conn);
command.ExecuteNonQuery();
conn.Close();
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)
{
}
}
I have a program that stores user projects as databases. Naturally, the program should allow the user to create and delete the databases as they need to. When the program boots up, it looks for all the databases in a specific SQLServer instance that have the structure the program is expecting. These database are then loaded into a listbox so the user can pick one to open as a project to work on.
When I try to delete a database from the program, I always get an SQL error saying that the database is currently open and the operation fails. I've determined that the code that checks for the databases to load is causing the problem. I'm not sure why though, because I'm quite sure that all the connections are being properly closed.
Here are all the relevant functions. After calling BuildProjectList, running "DROP DATABASE database_name" from ExecuteSQL fails with the message: "Cannot drop database because it is currently in use". I'm using SQLServer 2005.
private SqlConnection databaseConnection;
private string connectionString;
private ArrayList databases;
public ArrayList BuildProjectList()
{
//databases is an ArrayList of all the databases in an instance
if (databases.Count <= 0)
{
return null;
}
ArrayList databaseNames = new ArrayList();
for (int i = 0; i < databases.Count; i++)
{
string db = databases[i].ToString();
connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";";
//Check if the database has the table required for the project
string sql = "select * from TableExpectedToExist";
if (ExecuteSQL(sql)) {
databaseNames.Add(db);
}
}
return databaseNames;
}
private bool ExecuteSQL(string sql)
{
bool success = false;
openConnection();
SqlCommand cmd = new SqlCommand(sql, databaseConnection);
try
{
cmd.ExecuteNonQuery();
success = true;
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message.ToString());
}
closeConnection();
return success;
}
public void openConnection()
{
databaseConnection = new SqlConnection(connectionString);
try
{
databaseConnection.Open();
}
catch(Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void closeConnection()
{
if (databaseConnection != null)
{
try
{
databaseConnection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
The SqlConnection class polls the actual database connection. If you close the SqlConnection, the connection is returned to the Connection pool. To prevent this behaviour, set SqlConnection.Pooling = false;.
edit
John seems to be more to the point here. But you might have to keep polling in mind as well.
Two comments. First off, you should use a using statement and your could will be much cleaner.
More on topic, you are connecting to the database when you are trying to drop it! Connect to the master database instead.