I have SQL Server 2008 R2 installed and have the necessary databases created. Now I am trying to connect to the server through C# and failing miserably. I have tried several connection string formats from connectionstrings.com, but I still cannot connect to the database. This is the format I'm assuming I'm to use:
public static void connect()
{
string conString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword";
SqlConnection con = new SqlConnection(conString);
try
{
con.Open();
}
catch (Exception e)
{
Console.WriteLine("Unable to connect to database");
}
}
But I can't seem to identify the correct address and authentication (using windows authentication). How can I find the address in MSSM, and how would I properly use windows authentication?
Thanks so much.
Note: I am using Visual Studio 2010
Josh, you may want to consider using System.Data.SqlClient.SqlConnectionStringBuilder so you don't have to worry about the correct format.
edit: and when I actually look at your connection string, you say you're attempting Windows Authentication, but you provide a username and password. Instead, you want to do something like this:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
I found a way to cheat and find the connection string. Adding a new ADO.NET Entity Data Model in Visual Studio 2010 and importing a database from SQL 2008 R2 actually lists the connection string in the dialog box! I'm still going to use the SqlConnectionStringBuilder, but now I have the elements I need. Thanks for the input!
Related
Is there a way/code where I can use that won't require me to change my connection string everytime I move my project to another computer?
been using 2 computers with different server names, but with the same database.
PC1:
static string ConnStr = "Server=DESKTOP-Q0BI1S3;Database=ISPROJ2;Trusted_Connection=True;";
PC2:
static string ConnStr = "Server=DESKTOP//SEGUERRA;Database=ISPROJ2;Trusted_Connection=True;";
tried using: Server=(localdb)
Update: used localhost and (local) with PC1 worked fine, but these won't work with PC2
see img
I am not sure if this will work for you, but where I work everyone has their own local instance of sql server and each developer are using the db on localhost. We solve this problem by referencing the database as a dot (localhost).
"Server=.;Database=ISPROJ2;Trusted_Connection=True;"
This solution only works if all developers have their db installed as the default instance.
See here.
This may be the solution you are looking for. Use the hostname and append it to the connection string.
I also believe you may be able to use server=localhost;
You could make one computer work as a server and connect to it everytime with same connection string.
This might help you:
https://technet.microsoft.com/en-us/library/ms175483(v=sql.105).aspx
There are probably lots of libraries to solve this, but the simplest way you can do interim is to within the software identify which computer the software is run on:
static string GetConnectionString()
{
switch(System.Environment.MachineName)
{
case "PC1": //TODO:Change this to the actual machine name!
return "Server=DESKTOP-Q0BI1S3;Database=ISPROJ2;Trusted_Connection=True;";
case "PC1": //TODO:Change this to the actual machine name!
return "Server=DESKTOP//SEGUERRA;Database=ISPROJ2;Trusted_Connection=True;";
}
}
You can also make it more dynamic by reading it from the web.config/app.config:
static string GetConnectionString()
{
return ConfigurationManager.AppSettings["ConnectionString_" + System.Environment.MachineName];
}
This makes it more dynamic, and you can simply add a new connection string onto the web.config/app.config once it needs to run on a new environment.
<appsettings>
<add key="connectionstring_pc1" value="[pc1connectionstringhere!]"/>
<add key="connectionstring_pc2" value="[pc2connectionstringhere!]"/>
</appsettings>
You will find all SQL Server connection string options here.
https://www.connectionstrings.com/sql-server/
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
I have the version 9.1.131.0.
I want to connect to a Oracle 12 DB with a Service Name.
I have the login, pw, server, but it seems i can't add a service name or port to OracleConnectionStringBuilder.
How do i connect to my db with a service name?
I can make it happen with Oracle.ManagedDataAccess but due to performance issues i want to test if the Devart Driver is working better.
kind regards
Try SID instead of Service Name. I found this one: Using Direct Mode
SID** System identifier (Global Database Name)
** The Service Name connection string parameter can be used instead of SID, but in the Direct Mode you can connect only to one database instance (RAC isn't supported).
For me this works:
var str = new DbConnectionStringBuilder(false);
str.Add("Data Source", db);
str.Add("User ID", user);
str.Add("Password", pw);
var con = new Devart.Data.Oracle.OracleConnection(str.ConnectionString);
con.Open();
You can also put full connection string as data source instead of retrieving the alias from tnsnames.ora file, e.g.
string db = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={host})(PORT=1521))(CONNECT_DATA=(SERVICE_NAME={serviceName})))";
str.Add("Data Source", db);
So this is my conclusion:
Since I don't want my users to install the Oracle Client or a install package more than 10 MB, the Devart dotConnect Express for Oracle will not work.
Quote from exception:
"Express Edition doesn't support Direct mode. Do not use Direct parameter of connection string. Refer to dotConnect for Oracle editions matrix."
Thanks for the help.
Kind regards
I created a database name="records" with the help of SQL Server Management Studio (SSMS). Now my question if I uninstall SSMS then can I still access the database from a C# program? If yes, then then is the process for connectivity still same as given below?
SqlConnection cnn ;
string connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
cnn = new SqlConnection(connetionString);
Management Studio is just a GUI client for interacting with a database. It is separate from the actual database.
In other words: you don't need Management Studio to programmatically access a MS SQL database.
Shortest answer, yes.
The management tools are an optional extra, all you really need is the database server.
I'm creating a very basic CRUD desktop winforms application in C#/.NET 4.0.
Letting Visual Studio auto-generate the fields for the table I'd like to perform my CRUD operations on works just fine, but I'm running into problems when I try and interact with it manually with my own SQL queries.
The auto-generated fields are using the connection string:
Data Source=|DataDirectory|\Data Analysis.sdf
If I try and do:
SqlConnection conn = new SqlConnection(#"Data Source=|DataDirectory|\Data Analysis.sdf");
conn.Open();
It just hangs. What am I missing?
That's a connection string for a SQL Server Compact Edition (CE) database (everything stored inside a single .sdf file) - is that what you're using?
If so : in that case, you'd have to use SqlCeConnection (not a SqlConnection - that's for "grown-up" SQL Server version - not CE)
Maybe try adding some more options to the connection string:
Persist Security Info=False;
File Mode=shared read;
Believe you've specified a relative path to the .sdf file, where you might need to get the executable's runtime folder from System.Environment.CurrentDirectory and prepend it to the filename.
I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.