9
Answers

Opening database connection once outside of method but using in several different methods

Michael Reid

Michael Reid

14y
4k
1
Hi,

First of all I've only been programming in C# for a week or two and I am teaching myself so not completely confident with terminology or OOP.
I have a method which I am calling hundreds of times from various other methods. Inside this I am opening a database connection and running a query and returning a result.

Now I know that opening a new database connection hundreds of times is not very good - so I am trying to only open the database connection once on opening the program and closing the program.

I have pasted my method at the bottom of this post.

Now I was thinking I could open the database connection beside intizialize component and close it on exit - but the problem with this is I would then have to pass two extra variables to the method every single place I call it (which is hundreds of times) and also pass these variables to the dozen or so other methods I have which are calling the database method somewhere inside - which all becomes very messy and I would imagine is unnecessary if I could somehow just make the two variables public and accessible from all method.

So my question is there is any way of doing this - or at least a more simple way of trying to achieve this?

thanks.

P.S sorry for the bad formatting - this thing makes you type in your own html!?

--------------------------------------
My database method is as follows

private string CheckIfExists(String strSql)
{
string MyConString = "SERVER=***;" +
"DATABASE=***;" +
"UID=***;" +
"PASSWORD=***;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = strSql;


connection.Open();
Reader = command.ExecuteReader();

//return Reader.Read();
string xreturn = null;

while (Reader.Read())
{
xreturn = Reader["id"].ToString();
//MessageBox.Show(xreturn);
}

connection.Close();
return xreturn;
}

Answers (9)