I am attempting to connect to a local SQL Server database in C#.
I am currently using the following connection string:
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\majorWork\majorWork\gameStats.mdf;Integrated Security=True";
However, I do not want to use a hardcoded file path, as I wish to be able to use the application across multiple computers, where the file path will be different. How should I go about doing this?
Best way is set this connection in Web.Config file.
<Database>
<ConnectionString name="connection">Server=servername; Initial Catalog=dbname; Persist Security Info=False; User ID=username; Password=password; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30;;</ConnectionString>
</Database>
Then add Add System.Configuration as a reference.
in C# you can call this
string constring = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
After that you can create new connection instance by passing this to
SqlConnection con = new SqlConnection(constring)
If u install SQL server express using the default instance, then you can connect using . as your server name anyone can use it with default instance as well.
1.then in visual studio, click on solution explorer
2. Connect database, follow the instruction for SQL server
3. When it gets to server name use . to connect and choose your database name which you have created already in ms SQl, then test your connection
4. After it successful, u can now click on the database name showing under solution explorer,
5.after u click the database name, at the button right corner, there will be a connection string, copy it and use
This will be declared publicly or globally
Sqlconnection con = new sqlconnection("paste the connection string");
And to use
Sqlcommand cmd = new sqlcommand("insert into......",con);
Con.open ();
Cmd.executenonquery();
Con.close();
Related
Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.
A great resource I always keep around is connectionstrings.com.
It's really handy for finding these connection strings when you can't find an example.
Particularly this page applied to your problem
Attach a database file on connect to a local SQL Server Express instance
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
So here's the answer from MSDN:
Choos[e] "Add New Data Source" from the
Data menu.[And follow the connection wizard]
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
Click on Tools >> Connect to Database...
Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "AttachDbFilename" attribute and value. Example:
The raw text from the Advanced panel:
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
The actual entry in the web.config:
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
Just one more -- i've always kept a udl file on my desktop to easily create and test connection strings. If you've never done it before - create a new text file and name it to connection.udl (the ext is the only important part). Open the file, start on the Provider tab and work your way through. Once you're happy with the connection rename the file giving it a .txt extension. Open the file and copy the string - it's relatively easy and lets you test the connection before using it.
<add name="Your Database" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Expanse.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add
string constr = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=|DataDirectory|\myData.mdf; Integrated Security=True; Connect Timeout=30;";
using (SqlConnection conn = new SqlConnection(constr))
string constr = ConfigurationManager.ConnectionStrings["myData"].ToString();
using (SqlConnection conn = new SqlConnection(constr))
{
sqlQuery=" Your Query here"
SqlCommand com = new SqlCommand(sqlQuery, conn);
com.Connection.Open();
string strOutput = (string)com.ExecuteScalar();
}
The app works fine on my dev box but I take it to the end user's computer it gives this error. I published it and installed it on the target computer as well.
SqlConnection cs = new SqlConnection("SERVER=SERVERWITHDB;DATABASE=DATABASENAME;Trusted_Connection=True");
Is this the correct way to go about setting up a sql connection?
If you need to build the connection string inside your code (instead of configuring it in your exe.config file), you could use a SqlConnectionStringBuilder:
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "SERVERWITHDB",
InitialCatalog = "DATABASENAME",
IntegratedSecurity = true
};
SqlConnection cs = new SqlConnection(connectionStringBuilder.ToString());
You'll see that the connection string you showed in your question uses the wrong key words. A valid connection string for a SqlConnection looks like this:
SqlConnection cs = new SqlConnection("Data Source=SERVERWITHDB;Initial Catalog=DATABASENAME;Integrated Security=True");
So the keywords are:
Data Source for the database server name
Initial Catalog for the database to use
Integrated Security set to True for Windows authentication and False for SQL server authentication
User ID for the user name (SQL server authentication only)
Password for the password (SQL server authentication only)
You Need to check that the network user has access rights to SQL server (your integrated security was set to true).
This is my connection string
SqlConnection conn = new SqlConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
I copied it from the property, I added # in front but didn't change anything. There are no errors during Build and Run. But when I click insert button, the below error shows up.
"A network related or instance specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. "
I tried editing connection string and using datadirectory instead of the entire path, but the same error occurs, I am new to .net so I am unable to figure out what could be the cause. I tried google but I can't tell whether the solutions there are related to my problem.
Thanks in advance!
You're using the wrong type of SQL connection. You should be using the SqlCeConnection class:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
Here is a really good reference for SQL CE connection strings.
The data source for SQL Server is a machine name, not a file name.
You should add a reference to the SQL CE assembly, and do this:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
For MSSQL Server Compact Edition, you should use the SqlCeConnection class.
So this should work:
SqlCeConnection sqlConnection = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WFA1\WFA1\database.sdf");
Create you connection string as follow :
add in the namespace using System.Data.SqlServerCe;
SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\admin\documents\visual
studio 2010\Projects\WFA1\WFA1\database.sdf; Persist Security Info=False;");
if .sdf file inside you project then you can use :
string strConnectionString ="Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.
GetExecutingAssembly().GetName().CodeBase) + "\\database.sdf;Persist Security Info=False;";
SqlCeConnectionconn = new SqlCeConnection(strConnectionString );
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.
Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.
A great resource I always keep around is connectionstrings.com.
It's really handy for finding these connection strings when you can't find an example.
Particularly this page applied to your problem
Attach a database file on connect to a local SQL Server Express instance
Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
So here's the answer from MSDN:
Choos[e] "Add New Data Source" from the
Data menu.[And follow the connection wizard]
Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:
Click on Tools >> Connect to Database...
Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.
Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "AttachDbFilename" attribute and value. Example:
The raw text from the Advanced panel:
Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True
The actual entry in the web.config:
<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />
Just one more -- i've always kept a udl file on my desktop to easily create and test connection strings. If you've never done it before - create a new text file and name it to connection.udl (the ext is the only important part). Open the file, start on the Provider tab and work your way through. Once you're happy with the connection rename the file giving it a .txt extension. Open the file and copy the string - it's relatively easy and lets you test the connection before using it.
<add name="Your Database" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Expanse.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add
string constr = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=|DataDirectory|\myData.mdf; Integrated Security=True; Connect Timeout=30;";
using (SqlConnection conn = new SqlConnection(constr))
string constr = ConfigurationManager.ConnectionStrings["myData"].ToString();
using (SqlConnection conn = new SqlConnection(constr))
{
sqlQuery=" Your Query here"
SqlCommand com = new SqlCommand(sqlQuery, conn);
com.Connection.Open();
string strOutput = (string)com.ExecuteScalar();
}