When I add a database to a program, Visual Studio automatically creates the following connection string:
<connectionStrings>
<add name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString" connectionString="Data Source=|DataDirectory|\PlayerTeam.sdf" providerName="Microsoft.SqlServerCe.Client.3.5" />
<add name="PlayerTeamEntities" connectionString="metadata=res://*/edmPlayerTeam.csdl|res://*/edmPlayerTeam.ssdl|res://*/edmPlayerTeam.msl;provider=System.Data.SqlServerCe.3.5;provider connection string="Data Source=|DataDirectory|\PlayerTeam.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
I am trying to allow the user to select the database that they would like to open. How do I modify the connection string programmatically without losing my associated dataset and tableadapter?
Thanks in advance :)
you can use that method to call your connection string from your App.Config file to be used in the data connection or adapter
public string GetConnectionStringByName()
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
when you add a new database to your project it takes the same connection Name of the existing database plus a number by default.
so you can make the connection string as a variable and add the number to it when you add a new database.
Edit
By considering you will add databases to your project grammatically, then if you added a new data base.
it will take that connection string's Name:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
as it add a number at the end of the name of the existing database
so, you can invest the method i provided, to add the specified connection string Something like that:
public string GetConnectionStringByName(int DB_Number)
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString+Convert.ToString(DB_Number);
return returnValue;
}
as the DB_Number variable could be saved in an XML file in order not to be loosed and its increased each time you add database.
So, if you add a new database to the existing 1 the connection Name should be:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
and if you added another database the DB_Number will be increased by 1 to change the connection name to be :
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString2"
and enable the user to choose with connection string he wants to use.
on the other hand . if your databases added manually before the application runs.
it will be easier to Handle as what you just have to do is to save your connection string in a data structure as an array and call the wanted connection to use
that is what i figured out from your question
Related
I have my connection string set up in the app config but I can not get it to find that connectionstring or even see that the connection name currency is in the collection.
I tried to add a version.
I have tried to adding the provider name to the string.
I have moved it in and out and in again of the path where the database and solution are located.
I have carefully made sure that I was pointed to the right location on my computer.
<connectionStrings>
<!-- CHANGE THIS to match where your solution and sqlite database are -->
<add name="currency" connectionString="Data Source=F:\CurrencyExercise\currency.db" />
</connectionStrings>
And then the code that calls the above.
public BaseDataAccess(string connectionName = "currency")
{
_connectionName = connectionName;
Connection = new SQLiteConnection(ConfigurationManager.ConnectionStrings[_connectionName].ConnectionString);
Connection.Open();
}
I would expect the code to actually pull back a SQLiteConnection object rather than erroring out.
So, I'm writing a program that imports excel files to a database, finds matches, non matches, shows the tables, etc.
In the beginning I added manually just my database connection string, but I have to make my program let the connection string change.
In case none is inserted, it will use the last one inserted.
Behind code:
protected void BtnFazerTudo_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
connectionString = connectionString.Replace("{username}", TxtUtilizador.Text);
connectionString = connectionString.Replace("{pwd}",TxtPalavraPasse.Text);
connectionString = connectionString.Replace("{DataSource}", TxtHost.Text);
connectionString = connectionString.Replace("{Initial}", TxtBaseDeDados.Text);
Debug.Write(con);
}
Web Config:
<add name="Db" connectionString="Data Source ={DataSource} ;Initial Catalog=
{Initial};Persist Security
Info=True;User ID={username};Password={pwd}"/>
I already tried the String builder. I was able to output it in the debug window but I have no idea in how I transfer that connection made by string builder to other web forms.
The connection string you're creating needs to be stored somewhere so as all pages of your web application can access it. While there are some choices that let you pass data among pages none of them suits you mainly because (a) the connection string contains security sensitive information such as the password!!! and (b) they do not offer the level of persistence required by your scenario (unless you want the user to fill the textboxes every time he connects to your application).
Having said that, one viable option is to store the connection string in a database and retrieve it every time you need it. You can either store it as a whole string or each user data separately (i.e catalog, user id, password etc). In the latter case, you'd have to re-create the connection string every time you need it.
How you create the connection string has nothing to do with your original question. It is just about string concatenation in C# for which you can use the + or += operators, string interpolation or the String.Format, String.Concat, String.Join or StringBuilder.Append methods.
I am trying to connect to a SQL Server database in my website. I have created a database from Add -> Add New Item -> SQL Server database. The name of my database file is database.mdf.
I have created a ConnectionString:
<connectionStrings>
<add name="Khulna_website"
connectionString= "Server=(localDB)\\v11.0;Integrated Security=SSPI;Database=Database.mdf;"
providerName="System.Data.SqlClient" />
</connectionStrings>
My first question is, when I open a database that way, is it necessary to add a connection string? Asking that because I can already see a green connection line on the side of the database.
Then, how do I connect it on my C# code?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
The question is, what do I add on ["RegistrationConnectionString"] part? Should I give the name of my ConnectionString? Am I missing any point here? I am completely new here. Any help would be highly appreciated.
Yes, in order to connect to a database - you do need some form of a connection string - one way or another. It's typically considered a best practice to put those connection strings into a config file, so you can modify it without changing your code.
To retrieve the actual connection string from the config, you need to use the name=.... to you gave it in the config file:
<add name="Khulna_website"
*************** this is the **name** of your connection string
Retrieve it like this:
string conStr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
************** same name again
and then use it to create your connection object to the database:
SqlConnection conn = new SqlConnection(conStr);
Put the name of the connection string which is Khulna_website instead of RegistrationConnectionString
I have an application that consists of two forms. One form displays data returned from the database in fields and the other form opens a windows that allows the user to select which database to get the data from.
Currently, the application doesn't store the user's choice of database. I want to store what the currently selected connection string is each time the user selects the database they want to use in form2.
What is the best way to do this? If I made an instance of an object of a static class to store this information, would that persist the data for use on each form?
You should have an app.config configuration file, and in there, define a <connectionStrings> section:
<configuration>
<connectionStrings>
<add name="YourNameHere"
connectionString="server=.;database=AdventureWorks;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
You then add a reference to System.Configuration to your project, and then you can easily retrieve those connection strings:
string connStr = ConfigurationManager.ConnectionStrings["YourNameHere"].ConnectionString;
using(SqlConnection connection = new SqlConnection(connStr))
{
// do something here....
}
You could store the connection string in App.config and retrieve it like this:
string connStr = ConfigurationSettings.AppSettings["ConnectionString"];
public SqlConnection conn = new SqlConnection(connStr);
Example App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=DB;Integrated Security=SSPI;" providerName="Microsoft.SqlClient" />
</connectionStrings>
</configuration>
I would be tempted to use Application Settings for this purpose.
http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
This is a recommended place to keep your connection strings :-)
Though there are built-in .NET capabilites to store user related information (via Registry, config files, settings etc.) they seem to be too heavy.
I would recommend to use plain text file and keep it in user folder:
var userPath = Environment.GetFolderPath(Environment
.SpecialFolder.ApplicationData);
var filename = Path.Combine(userPath, "mysettings");
// Read connection string
var connectionString = File.ReadAllText(filename);
// Write connection string
File.WriteAllText(filename, connectionString);
Also note that hardly users will have fun working with connection strings. They would prefer to specify database name, server, username etc. using separate form fields. To map those fields to connection string you may use SqlConnectionStringBuilder class (if you are working with MSSQL Server):
// to connection string
var connectionStringBuilder1 = new SqlConnectionStringBuilder();
connectionStringBuilder1.DataSource = "server";
connectionStringBuilder1.InitialCatalog = "database";
var connectionString = connectionStringBuilder1.ConnectionString;
// from connection string
var connectionStringBuilder2 = new SqlConnectionStringBuilder(connectionString);
var serverName = connectionStringBuilder2.DataSource;
var databaseName = connectionStringBuilder2.InitialCatalog;
So here's the what's up. I just created and "published" a staff management tool in Visual C#. During development, I used a string saved in Properties.Settings.Default to connect to the database I was using for development. Now since the solution is published and ready to go, the boss wants to connect to the real staff database. I was under the impression that connection to the new database would be as simple as changing the connection string in some properties file somewhere. Unfortunately I can't seem to find the proper file/string to connect to the database I want to. Any ideas?
Thanks!
JB
Look here:
Connection Strings and Configuration Files
By using a config file you just have to change the config file connection string once your application has been deployed.
Here's a way of doing what you want:
From http://www.dreamincode.net/forums/topic/70745-connection-string-in-appconfig/
Your config file content:
<connectionStrings >
<add name="YourName"
connectionString="Provider=msdaora;Data Source=MyOracleDB;Persist Security Info=False;Integrated Security=Yes;"
providerName="System.Data.OracleClient" />
</connectionStrings>
Method to get the connection string at runtime:
public static string GetConnectionString(string strConnection)
{
//Declare a string to hold the connection string
string sReturn = new string("");
//Check to see if they provided a connection string name
if (!string.IsNullOrEmpty(strConnection))
{
//Retrieve the connection string fromt he app.config
sReturn = ConfigurationManager.ConnectionStrings(strConnection).ConnectionString;
}
else
{
//Since they didnt provide the name of the connection string
//just grab the default on from app.config
sReturn = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString;
}
//Return the connection string to the calling method
return sReturn;
}
Using the method:
string connectionString = GetConnectionString("YourName");
I've had to change the entry in the Properties.Settings text file, recompile and redeploy to get the new connectionstring to take. In the future consider reading your connection string from your .config file under either the ConnectionStrings or AppSettings node. When you store it there you simply need to change a production text file to switch your database...