How to get the connection String from a database - c#

I have created a database with SQL Server Management Studio, I would like to now use it in my C# application. I need the connection string?
Where can I find the connection string, and where is my database stored?
Do I have to publish it or something like that, or is it in my documents somewhere?
using (var conn = new SqlConnection("your connection string to the database"))
How do I obtain the connection string? Where can I find the connection string to copy paste into the above section?
How to I publish my database so that Visual Studio can pick it up? Then I can just pull the connection string of there?

The easiest way to get the connection string is using the "Server Explorer" window in Visual Studio (menu View, Server Explorer) and connect to the server from that window.
Then you can see the connection string in the properties of the connected server (choose the connection and press F4 or Alt+Enter or choose Properties on the right click menu).
Advanced connection string settings: when creating the connection, you can modify any of the advanced connection string options, like MARS, resiliency, timeot, pooling configuration, etc. by clicking on the "Advanced..." button on the bottom of the "Add connection" dialog. You can access this dialog later by right clicking the Data Connection, and choosing "Modify connection...". The available advanced options vary by server type.
If you create the database using SQL Server Management Studio, the database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express / localDB installed on your machine for this to work.

A very simple way to retrieve a connection string, is to create a text file, change the extension from .txt to .udl.
Double-clicking the .udl file will open the Data Link Properties wizard.
Configure and test the connection to your database server.
Close the wizard and open the .udl file with the text editor of your choice and simply copy the connection string (without the Provider=<driver>part) to use it in your C# application.
sample udl file content
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;Initial File Name="";Server SPN=""
what you need to copy from it
Integrated Security=SSPI;Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;
If you want to specify username and password you can adopt from other answers.
Tutorial: https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/

Open SQL Server Management Studio and run following query. You will get connection string:
select
'data source=' + ##servername +
';initial catalog=' + db_name() +
case type_desc
when 'WINDOWS_LOGIN'
then ';trusted_connection=true'
else
';user id=' + suser_name() + ';password=<<YourPassword>>'
end
as ConnectionString
from sys.server_principals
where name = suser_name()

If you have installed and setup MS SQL Server and Management Studio, go to Visual Studio (Visual Studio not SQL Server Management Studio).
1] In Visual Studio go to Tools -> Connect to Database.
2] Under Server Name Select your Database Server Name (Let the list Populate if its taking time).
3] Under Connect to a Database, Select Select or enter a database name.
4] Select your Database from Dropdown.
5] After selecting Database try Test Connection.
6] If Test Connection Succeeds, Click Ok.
7] In Visual Studio go to View -> Server Explorer.
8] In Server Explorer window, Under Data Connections Select your Database. Right Click your Database -> Click Properties.
9] In Properties window you will see your Connection String.

On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress, write the name of your installed instance (by default it's .\SQLEXPRESS for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI.

My solution was to use excel (2010).
In a new worksheet, select a cell, then:
Data -> From Other Sources -> From SQL Server
put in the server name, select table, etc,
When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.
And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)

If one uses the tool Linqpad, after one connects to a target database from the connections one can get a connection string to use.
Right click on the database connection.
Select Properties
Select Advanced
Select Copy Full Connection String to Clipboard
Result: Data Source=.\jabberwocky;Integrated Security=SSPI;Initial Catalog=Rasa;app=LINQPad
Remove the app=LinqPad depending on the drivers and other items such as Server instead of source, you may need to adjust the driver to suit the target operation; but it gives one a launching pad.

put below tag in web.config file in configuration node
<connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
providerName="System.Data.SqlClient" />
then you can use above connectionstring, e.g.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();

The sql server database will be stored by default in the following path
<drive>:\Program Files\Microsoft SQL Server\MSSQL.X\MSSQL\Data\
, where <drive> is the installation drive and X is the instance number (MSSQL.1 for the first instance of the Database Engine). Inorder to provide the connection string you should know what is the server name of the sql server database, where you have stored followed by instance of the database server.
Generally the server name will be like the ip address of the machine where the database is attached and the default instance will be SqlExpress
A connection string contains Data Source name i.e., server name, Initial catalog i.e., database name, user id i.e., login user id of the database, password i.e., login password of the database.

Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...

If you created Connection Manager in your project then you can simply pull the connection string from there.
String connection = this.dts.connections["<connection_manager_name>"];
And use this connection in:
using (var conn = new SqlConnection(connection))
Please correct me if I am wrong.

SqlConnection con = new SqlConnection();
con.ConnectionString="Data Source=DOTNET-PC\\SQLEXPRESS;Initial Catalog=apptivator;Integrated Security=True";

Related

Working with Sample Databases

I have been working with SQL-Server for awhile as part of my weekly routine, and since everything was setup in advance, I take everything for granted.
Start SQL Server, pick a Server name, pick SQL Server Authentication, then type my login and password
or from an application just use a given connection string and everything works like charm
Until all the sudden, a third party sent me an application sample that needs to be reviewed, and it includes a Northwind database, and from that point on I am having difficulty getting this sample to work.
Changing the connection name and pass to match SQL Server instance credential does not solve the problem
This is how my string usually looks like
I have SQL Server 2014 installed and also this is how the application folder structured
In Server Explorer in Visual Studio the connection is recognized and when I attempt to access, I get
How to think about this problem in order to solve it and get the sample running? There is a missing gap that I cannot point my finger to.
I have two solutions for you.
In Visual Studio, create a class library project. Delete the default class file. Right click the project name -> Add -> New item -> Select "ADO.NET Entity Data Model" name it what you want and click Add. Make sure "EF Designer from database" is selected and click Next. Click New Connection. Next to "Data Source" click Change. Select "Microsoft SQL Server Database File", click OK. Click Browse and select the .mdf file for the database. Select "Use SQL Server Authentication" and provide your login credentials, then click Test Connection. If the connection fails, your login is wrong (minus a random super rare occurrence). Click OK and finish out the menus. Go into the App.Config and copy the entire xml tag. Go into your application project, right click, the project name -> Manage NuGet Packages -> Browse -> Search for EntityFramework, select it and click Add on the right hand side. Accept the terms it provides. Go into your application projects App.Config and paste the xml tag you copied into the xml tag. To use it, copy the value of the name attribute from the tag from earlier and do the following
using (var db = new NameAttributeFromAddTag())
{
// Use standard link notation
var item = db.TableName.Where(i => i.Id == idYouWant);
}
(You can find more info about adding the connection here: https://msdn.microsoft.com/en-us/library/jj206878(v=vs.113).aspx)
Open up SQL Server Management Studio and connect wherever you want to (Such as computerName/SQLExpress (your default local DB server)). Right click Databases -> Attach -> select .mdf file for the database. Click Ok, click Ok again. Connect to that database as you would any other database. If it still says your login is incorrect, In SQL Server Manager look at Databases -> yourDatabase -> Security -> Users and check the properties of the user you are trying to use.
This is precisely how I got it to work:
Install SQL Server Express edition (Not SSMS)
Open SQL Server Management Studio (SSMS) and enter parameters as seen
Attach Database mdf file
In the application Config file add a connection string similar to
As a note:
.\sqlexpress Server name or Data Source in the connection string could be replaced with (local)\sqlexpress
I found this by chance while querying data in SSMS and looking at the bottom:
Also found this answer useful in explaining that dot, (local) and Computer name are all equivalents

don't know Connection string parameter in C#

i am developing an application in C#,i have create database1.mdf by
right clicking on my project,add item
then creating a database.
my intial problem was,i was able to execute query correctly but those modification wasn't reflected in main database
finally after lot of surfing i changed copy to output directory to copy if newer but still i am not able to rectify my problem.
now i am feeling that i need to connect to sqlserver using connectionstring but i don't know username,servername,password etc...
can anyone help me please
if you want to connect database in csharp so visual studio will help you to connect with database
go to solution explorer right click on project and add new item and select service-base database click add.
Now Go to Server explorer look there is database with .mdf extension
expand it right click on table and create table your self.
After creating table you need connection string to connect your application to database.
you connection string look like this
string databaseFileName="Your database file with .mdf extension like database1.mdf";
string connectionString=#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\"+databaseFileName+";Integrated Security=True";
SqlConnection conn=new SqlConnection(connectionString);
conn.Open();
Console.writeLine(conn.State.ToString());/*this will show your database state is open or close.
Note:Here i am using visual studion 2013 other (LocalDB)\v11.0 this could be changed .

How to change SQL Server 2005 from Windows Authentication to SQL Authentication?

I have installed SQL Server 2005 in Windows Authentication, now I want to change it to SQL Authentication.
However, I cannot reinstall SQL SERVER and Management again, because it will lose the data in it.
Also I want to know what changes do I need to make in my Connection class to open connection, as my current is
public SqlConnection con= new sqlConnection("server=.\\SQLEXPRESS;database=Restaurant;integrated security=sspi");
Just need to ask one more thing, I can see my database in WIndows Auth and in SQL auth, so how can i change, so that any other user need to login before it peeps into my database. thanks
Using SQL Server Management Studio
*To change security authentication mode*
In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties.
On the Security page, under Server authentication, select the new server authentication mode, and then click OK.
In the SQL Server Management Studio dialog box, click OK to acknowledge the requirement to restart SQL Server.
In Object Explorer, right-click your server, and then click Restart. If SQL Server Agent is running, it must also be restarted.
To enable the sa login
In Object Explorer, expand Security, expand Logins, right-click sa, and then click Properties.
On the General page, you might have to create and confirm a password for the login.
On the Status page, in the Login section, click Enabled, and then click OK.
Using Transact-SQL
To enable the sa login
In Object Explorer, connect to an instance of Database Engine.
On the Standard bar, click New Query.
Copy and paste the following example into the query window and click Execute. The following example enables the sa login and sets a new password.
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '<enterStrongPasswordHere>' ;
GO
You can pass below sample(change appropriate UID & PWD) connection string in your connection object
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
To use SQL Server authentication, change the line:
public SqlConnection con= new sqlConnection("server=.\\SQLEXPRESS;database=Restaurant;integrated security=sspi");
to
public SqlConnection con= new sqlConnection("server=.\\SQLEXPRESS;database=Restaurant;user id=#USERID#;password=#PASSWORD#;Trusted_Connection=False");
Where "#USERID#" and #PASSWORD# are the specific User ID and Password respectively
To change the server security type:
You just need open SQL Server Management Object Explorer, right click the server, go in Properties, Security page, under server authentication, select the mode you want.
To modify the connection string:
1. You need to have a SQL user first. Still in the SQL Server Management Object Explorer, right click on user which under Security node, click new, then you can create one.
2. add the "User ID" and "Password" segment to the connection string.

Connect to remote SQL Server 2008 on Visual Studio 2010

I created a local MSSQL database with my ASP.NET project.
Now I want to connect to my database hosted in www.abc.com
What should I put in the connectionString ?
Check with your hosting provider (abc.com). Some hosting providers don't allow remote connection to their databases, and require you to use their web application to access your database.
If they do allow access, they should provide you with SQL Authentication details of:
Server Name
Database Name
Username
Password
An example of a SQL connection string would be:
Data Source={server name/ip};Initial Catalog={database name};User ID={username};password={password}; MultipleActiveResultSets=True;
See http://www.connectionstrings.com/sql-server-2008
You may use Server Explorer tool of Visual studio to get the connection string. (Right click on Data Connections + Add Connection).
"Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"
or
"Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;integrated security=true"

Backup Sql Express

I would like to be able to run an on demand backup of a .Net MVC app's SQL Express 2008 database to eg a flash stick plugged into the machine running the app.
I tried
QuickstemDataContext db = new QuickstemDataContext();
string quickstem_path = Path.Combine(save_path, "quickstem.backup");
db.ExecuteCommand(string.Format("BACKUP DATABASE {1} TO DISK = '{0}' WITH COMPRESSION;", quickstem_path, db.Mapping.DatabaseName));
But get the exception
Database 'quickstem' does not exist. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally
I am using the following connection string.
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quickstem.mdf;Integrated Security=True;User Instance=True"
Do I need to attach the DB using something like Express Management Studio and give it a name etc. Ideally I want to keep the app deploy very simple without having to setup sql management studio etc. Can this attaching be done another way or can a Backup be done with out needing to attach
I tried giving it the full path of the .mdf file instead of the database name but got a syntax error on c:
You'll find that if you add Database=Quickstem to your connection string, your backup code will work just fine.
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quickstem.mdf;Integrated Security=True;User Instance=True;Database=Quickstem

Categories

Resources