简体   繁体   中英

How to connect an application to a SQL Server using IP Adress in C#?

My problem is that I have created a SQL Server database but I access it locally, only from my own computer. What I want to do is to connect the app to a server and to save all the data there.

The code I used to connect to the SQL Server database is:

SqlConnection con = new SqlConnection(@"Data Source=(localdb)\v11.0;AttachDbFilename=C:\Users\donca\Desktop\Memo\Memo\ContNou.mdf;Integrated Security=True");

SqlCommand cmd1 = new SqlCommand("SELECT * FROM [dbo].[Cont] WHERE Nume_utilizator = @Nume_utilizator and Parola = @Parola;", con);

cmd1.Parameters.AddWithValue("@Nume_utilizator", this.Nume_utilizator.Text);
cmd1.Parameters.AddWithValue("@Parola", this.Parola.Text);

cmd1.Connection = con;
con.Open();

My question is: how can I change this to connect and access data from a SQL Server and save data there?

Just change the connection string: "Data source=ServerName\\InstanceName;"

You can use the IP address instead of the servername. The default instance name is MSSQLSERVER.

Make sure you turn on "Remote connections" on the distant server. You can use Management studio -> Server properties -> connections -> Allow remote connections.

If it dosn't work check that the TCP/IP protocol is activated for you instance.

You can find it in SQl Server Configuration Manager.

You just have to change your connection string. That's all. For an example, if your server name is CORP and the SQL instance name is SQL2012, your connection string will be like this.

SqlConnection con = new SqlConnection(@"Data Source=CORP\SQL2012;Initial Catalog=ContNou;Integrated Security=True"); 

In case if you cannot find the SQL server by its name, you can use the IP too.

SqlConnection con = new SqlConnection(@"Data Source=10.4.2.208;Initial Catalog=ContNou;Integrated Security=True"); 

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