Maintain a single database connection in multiple forms - c#

I have this c# application where the user needs to login through the first form. If validation returns true form2 opens up .
I want to maintain a single connection through all these forms with the same user credentials as entered in form1.I am using ODP.NET to connect to oracle 11g.
Thanks.

Sql connection in .NET is managed by connection pool. So if you instantiate new connection objects, it reuses old closed physical connection.
in form1
using(var c = new SqlConnection("connectionstring"))
{
//use connection here
}
in form2
using(var c = new SqlConnection("connectionstring"))
{
//use connecion here
}
form1 and form2 use same physical connection to database
connection pooling also available for Oracle Data Provider
or maybe you interested in Entity Framework

Create a Static Connectionstring class like
if you declare a Static class with properties of Sqlconnection you can access it in any form or any other class directly here is a sample of class
public static class Connection
{
private static SqlConnection sqlconn;
public static SqlConnection getconnection() {
if (sqlconn==null)
sqlconn = new SqlConnection("Connectionsting.");
return sqlconn;
}
}

Related

Simple SQL Server database connection and reading a table on C#

I am new at this but I have a simple table in my SQL Server with one column name and 2 rows in it. I am trying to show up the names when pressing a button, I need to know how to connect the SQL Server database to the C# code and how to read from a specific table.
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=DESKTOP-REB699D\SQLEXPRESS;Initial Catalog=DBdemo";
cnn = new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
}
}
}
But that didn't work, it crashes at the cnn.open(); line of code.
If you are not using any credentials, its windows authentication.
Does adding Integrated Security=True to the connection string help?
Can you login to the DB without credentials on SSMS using Windows authentication option? If so, you don't need user credentials for connecting to DB. If you require a Username and password there,
you either need to include that in the connection string or
you need to enable SQL Server and Windows Authentication option under security tab to access the database without credentials

Can't use MySqlConnection methods outside function

I am new coding and I am trying to create a model DBContext.
I instantiated a connection conn using MySqlConnection. Then I perceived it didn't me allow to use conn methods (like conn.Open()).
I have found a code that uses it inside a function and it seems to work. However I couldn't understand why it has to be inside a function.
Here is my code:
public class DBContext
{
//Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
//start creating connection string
public static string ConnectString
{
get { return "Server=localhost;Database=blog;Uid=root;Pwd=root;"; }
}
public string ConnectionTest()
{
//create an instance of connection
MySqlConnection conn = new MySqlConnection();//Here I can use conn properties/methods
return "";
}
//create an instance of connection
MySqlConnection conn2 = new MySqlConnection();//Here I can't
conn2.open();
}
After reading some documentation about classes and method I understand that classes are references therefore it will not "run".
However I couldn't understand why the error when using conn2.open() is
conn2.open() does not exist in the current context.
shouldn't conn2 exist in the "class context"?

OleDbConnection: How to open and close a connection using a function

I have a function that connects to a Excel File:
public OleDbConnection connection;
public void eConnection(string srcString, string id)
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
connection = new OleDbConnection(conString);
connection.Open();
}
I want to create another function that will close this existing connection when called or invoke
This is what I have to try and close the existing connection:
public void eCloseConnection()
{
connection.Close();
}
How can I close the existing connection using a function that calls the same connection and closes it
How can I test to see if the connection is closed?
Don't do it like this. OleDbConnection implements the IDisposable interface should be disposed as soon as you are done using it, and the best way to do it is to use it as a local variable declared in a using statement:
public void DoStuffWithExcel(string srcString)
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
using(var connection = new OleDbConnection(conString))
{
connection.Open();
// do your stuff here...
}
}
The using statement ensures the connection will be disposed properly even if an exception occurs inside the using block.
This way is the best way to prevent memory leaks, as well as to use the connection pool.
From Microsoft docs page OLE DB, ODBC, and Oracle Connection Pooling:
We recommend that you always close or dispose of a connection when you are finished using it in order to return the connection to the pool. Connections that are not explicitly closed may not get returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be returned to the connection pool if the maximum pool size has been reached and the connection is still valid.
Don't keep a global object for a connection hidden inside a class. This adds more problems than the one solved. You should keep track how many time that code is called and how many connection it creates. And of course this makes a lot more complicated the closing part.
Instead the C# language offers a better approach to this kind of problem. An approach particularly suited for objects like a connection that requires unmanaged resources to be realeased to the OS as soon as possible.
You should instead use this approach both if you want to have a class that handles your connections or if you just want to open and use a connection
public static class DbUtility
{
public static OleDbConnection eConnection(string srcString)
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + srcString + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
connection = new OleDbConnection(conString);
connection.Open();
return connection;
}
.... other static utilities
}
Now you can use your class in this way
string srcFile = #"d:\temp\myFile.xlsx";
using(OleDbConnection cn = DbUtility.eConnection(srcFile))
{
.. use your connection
} // <- at this point your connection is automatically closed and disposed.
The using keyword is of great help when you need to just destroy your disposable objects like a connection. In this way you don't keep a global object around when you don't need it.

C# Run SQL Query on another machine

Recently we have had an issue with our ERP retrieving some information from our database tables. While this is being fixed I have come up with some work arounds to temporarily, however, they only work because my user has access to the SQL database and can run queries on the database. I would like to distribute an executable program throughout the company (we are relatively small, so I am not worried about bottle-necking my computer) that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. This way we don't need to make any changes to users SQL permissions.
How could I possibly do this?
Edit - Additional Info
User A - has permission to query the database on our servers from
their workstation
User B - does not have permission to query the db
User B needs to gather information from a specific db query, yet they don't have access to the db. All that User B needs, is to be returned a string with information from that query.
So not necessarily looking for the remote execution of a program per se, because then how would they get that return value?
I would do it with an application that does something like this.
using MySql.Data.MySqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection conn = null;
try
{
conn = new MySqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
MySqlCommand selCmd = new MySqlCommand("SELECT ...", conn);
MySqlDataAdapter da = new MySqlDataAdapter(selCmd);
....
This uses MySql, but the exact equivalent can be done with any DB provider. The part of the connection string that says Integrated Security=False tells the system not to use the current user's window credentials but rather what is being provided in the connection string.
The same thing but using Sql Server, I think, would be like this (it's been a while since I use sql server...
using System.Data.SqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
SqlCommand selCmd = new SqlCommand("SELECT ...", conn);
SqlDataAdapter da = new SqlDataAdapter(selCmd);
....
I assume based on the quote below - you are creating a program that you will send to user B to use to run the query and return a string.
"that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. "
If this is the case - User B doesnt need any data base permissions. You will put your [user A]'s username and password in the connection string of the program you create. So when User B runs this program you gave him, it will use User As permissions to run and return data.
like this:
<add name="myconnection" connectionString="data source=yoursqlserver;initial catalog=yourdataabase;persist security info=True;user id=UserA;password=userAspassword" providerName="System.Data.SqlClient" />

How to connect to database in C# using SqlConnection object?

How can I connect to a remote or local database using simple SqlConnection object? I learned to do it this way, but my connection is failing. I read about creation of connection string from this page:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
My code:
using System.Data.SqlClient;
namespace SyncApp_BuiltInProviders
{
public partial class Form1 : Form
{
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection source_conn = new SqlConnection();
source_conn.ConnectionString ="Server=localhost;Database = ptls; UID = root;Password = ODYSSEY99GRANITE;";
source_conn.Open();
}
}
}
As from your comment in another answer it is clear that you are using the wrong classes. The SqlConnection is a class specialized in connecting to Sql Server/Sql Server Express/LocalDb. It cannot work against a MySql
If you use MySql then you need to download and install the MySql Connector for NET from here.
After that, you need to reference the MySql.Data.dll and add a
using MySql.Data.MySqlClient;
to all the source files that interact with the database.
Finally, all the classes used to work with the database, should be the ones provided by the MySql NET Connector.
They are prefixed with MySql..... (MySqlConnection, MySqlCommand, MySqlDataReader etc.)
If you are used SQL Database, it seems to me that, you have not set username and password. If you have not set username and password then try this.
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection db_connect= new SqlConnection();
db_connect.ConnectionString ="Server=[your local pc connection name, it is not local host.];Database=[database_name];Trusted_Connection=true";
db_connect.Open();
}
If you use MySql then
private void btnSynchronize_Click(object sender, EventArgs e)
{
//Create a MySQL connection string.
string connectionString="Server=localhost;Database[database_name];Uid=root;Password =your password; ";
MySqlConnection db_connect= new MySqlConnection(connectionString);
db_connect.Open();
}
Finally use following name space
using MySql.Data.MySqlClient;

Categories