I know work with db.So i in my class have static object:
static private MySqlConnection conn = null;
public static Boolean postoji(String username, String password)
{
conn = new MySqlConnection("Server=127.0.0.1;Database=cs322;Uid=root;Password =; ");
Boolean rez=false;
try
{
conn.Open();...
In this class i have 5 mehtods,so i thinking,does is better to have this static object null,and initialization them in every method.Or have static object which is alrady created.
private MySqlConnection conn== new MySqlConnection("Server=127.0.0.1;Database=cs322;Uid=root;Password =; ");
and methods just use them.
I would say better would be have this connection string in your web.config or app.config and read it from there instead of defining your connection string in code. So that in future if your connection string needs change you know only one place change would present as well editing config file doesn't need you to re-publish your code.
You should be putting all the connection string in the configuration file. Below is the code sample for putting and reading it from confile fie.
web config file
<add name="ConnectionStringName" connectionString=127.0.0.1"; Initial Catalog=cs322; Integrated Security=True"/>
Also same time i would suggest to wrap your connection within the Using block like below example.
Reading code from code behind
using(MySqlConnetion connection = new MySqlConnetion(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
{
connection.open();
//setup and execute query
} //connection gets closed here
Here, once you exit the using block, the connection is closed.
Related
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.
I have my connection string stored in App.Config
<connectionStrings>
<clear />
<add name="CTaC_Information_System.Properties.Settings.CIS_beConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source="\\server\file\CIS Data\Database\CIS_be.accdb"e;;Jet OLEDB:Database Password=123"
providerName="System.Data.OleDb" />
Then when I go to my main.xaml.cs I type in the following:
string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;`
I found that answer on Stack Overflow when searching, but some were say to put var but when I typed var it wouldn't recognize it so I went with the string method.
When I go to type cisconn.Open(); the option isn't there. I am referencing System.Configuartion;,System.Data.Sql; System.Data.SqlClient; and System.Data.OleDb;.
Can someone show / tell me how I can connect to the database from c#? I'm trying to test the connection when my application runs but I can't figure it out.
The connection string is just a string, its meant to be used in your connection, so you should do:
public void DoSomeDatabaseOp()
{
string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(cisconn))
{
conn.Open();
//Create your commands or do your SQL here.
}
}
You should create/destroy the connection inside the method you are using it in. Don't keep a reference to it in the root of the class object. This keeps the connections clean and open if you aren't doing database operations.
If you really wanted to though, you could do this:
class MyClass
{
OleDbConnection _rootConn;
string _connStr;
public MyClass()
{
_connStr = string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
_rootConn = new OleDbConnection(_connStr);
}
public void DoSomeDatabaseOp()
{
//Use _rootConn here
}
}
BUT the class should implement IDisposable so that it can dispose of the connection properly! How to implement IDisposable is beyond the scope of the answer, but look up how to implement it properly.
I'm trying to use Entity Framework and it put it's connection string into app.config. I would like to move it to code as it's easier for me at this stage of development.
metadata=res://*/database.csdl|res://*/database.ssdl|res://*/database.msl;provider=System.Data.SqlClient;provider connection string="data source=computer;initial catalog=database;persist security info=True;user id=user;password=Mabm#A;multipleactiveresultsets=True;App=EntityFramework"
How can I make Entity Framework use connection string from code rather then look at the app.config? Alternatively if it's not possible how can I pass parameters to app.config (like dbname, dbuser, dbpassword)?
You can use EntityConnectionStringBuilder for this purpose.
Check here
public string GetConnectionString()
{
string connectionString = new EntityConnectionStringBuilder
{
Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
IntegratedSecurity = false,
UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
Password = ConfigurationManager.AppSettings["SystemDBPassword"],
MultipleActiveResultSets = true,
}.ConnectionString
}.ConnectionString;
return connectionString;
}
When you create an instance of your ObjectContext derived class, you can simply pass the connection string as a constructor argument.
Rather than use a username and password, why not use Integrated Security? It is more secure and easier to manage.
i.e. 'Trusted_Connection = Yes' in your connection string and securely manage access through AD.
Connection Strings
First, create your context using the constructor with the connectionString parameter.
http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx
Note that it's not directly this constructor that you must call, but the specific inherited context constructor for your database that your Entity generator created for you.
Furthermore, if you want to pass the username and password at runtime, you can create a connection string using this class:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
See here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx
If the connection string log in details are always the same then I would suggest that you use ConfigurationManager to retrieve the connection string from your app.config and encrypt the ConnectionStrings section of the file.
Is there an existing method in C# to extract the file path from a string that represents a ConnectionString to a SqlCE .sdf file? I want to check if the file exists at initialization and back it up if the file has been modified.
Sample connection string:
strConn = "Data Source=|DataDirectory|\dbAlias.sdf";
You can use SqlCeConnectionStringBuilder class to parse existing Sql Compact connection string.
A bit late perhaps, but I came across this question wile struggling with the same problem. You can find the location of the |DataDirectory| folder with AppDomain.CurrentDomain.GetData("DataDirectory"). So your connectionstring can be translated like this:
strConn .Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString())
You could just create the connection and get the data source from it as a property:
string data;
using (var conn = new SqlConnection(connectionString)) {
data = conn.DataSource;
}
For LocalDB and SqlConnection (not CE):
public static string GetFilePathFromConnectionString(string connectionString)
{
var attachDbFileName = new SqlConnectionStringBuilder(connectionString).AttachDBFilename;
return attachDbFileName.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
}
If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)