tp07
tp07

Reputation: 39

Connect to a SQL Server database without a set file path

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?

Upvotes: 0

Views: 1376

Answers (2)

CodeMind
CodeMind

Reputation: 646

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)

Upvotes: 1

Haywhy
Haywhy

Reputation: 31

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();

Upvotes: 0

Related Questions