简体   繁体   中英

C# Auto use of PC Name in Connection String

Is there a possible way to use your program with any computer with out changing a connection string? By the way, I'm using Visual Studio 2008 for creating a windows form application and Microsoft SQL SERVER MANAGEMENT STUDIO 2012 for my database.

And here are some of my codes, this is my class konek

class konek
{
    SqlConnection conn;
    public SqlConnection getConnect()
    {
         conn = new SqlConnection(@"Data Source='" + System.Windows.Forms.SystemInformation.ComputerName + "'\\SQLEXPRESS;Initial Catalog=it12-ProjectMedicalAssistance;Integrated Security=True");
         return conn;
    }
}

And this is my way of using it to my other window forms for me to access the database

conn = koneksyon.getConnect();
conn.Open();

Just use .\\SQLEXPRESS. The . (dot) is already equivalent to your local machine name - Credits to @haim770 for the answer

Data Source=.\SQLEXPRESS;Initial Catalog=it12ProjectMedicalAssistance;Integrated Security=True

You can utilize the connection string like this

Data Source=.\sqlexpress;Initial Catalog=test;Integrated Security=True

or

Data Source=(local)\sqlexpress;Initial Catalog=test;Integrated Security=True

. and (local) and YourMachineName are all equivalent, referring to your own machine.

It is also possible to use port number in connection string in case of named SQL Server instances as below. You need to know which port is being used by your named instance. If you know the port number then even the instance name is not required. Machine name and port number combination is enough to make SQL connection:

Data Source = (local),5122;Initial Catalog=test;Integrated Security=True

OR

Data Source = myMachineName,5122;Initial Catalog=test;Integrated Security=True

OR

Data Source = .,5122;Initial Catalog=test;Integrated Security=True

On my machine the named instance was using port # 5122.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM