简体   繁体   中英

How to connect to SQL server via TCP/IP which is server site using C#?

Everyone. I've got some questions here.. I'm using C# and trying to connect the other computer which is server site. The server site has been built a large database and it can be accessed by SQL server manager 2012. All I'm trying is to read the data in that database then convert to the other file. The other project test in my computer works(self-connection), but Here's my sqlconnection string:

string sqlstring = @"Data Source=XXX.XXX.XXX.XXX\SQLEXPRESS,1433;Network Library=DBMSSOCN;Initial Catalog=Database; Integrated Security=False; Connect Timeout=30;User ID=sa;Password=XXXXXXX";

Do I need to add "AttachDbFilename" into there?

or even database path?

AttachDbFilename=""C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Databasename.mdf"

Because the results are "sa log in failed" or "it couldn't find the database file".. Is there any good advice? thank you guys!

If you don't really know what arguments the connection string takes you may want to look into the SqlConnectionStringBuilder .

Here is a short code snippet:

SqlConnectionStringBuilder connString = new SqlConnectionStringBuilder();
connString.UserID="sa";
connString.Password = "XXXX";
connString.DataSource = "XXXX"; //if you need to specify a port write
                                // the portnumber with a ',' behind the address
connString.InitialCatalouge = "MyDatabaseName";
connString.IntegratedSecurity = false; //set this one true if you want to use windows
                                       //authentification instead of sql authentification
string myconnectionstring = connString.ConnectionString;

It is a bad idea to use the super user, consider making a user that has only the privileges you need for your application to minimize security risks.

"Data Source=XXXXX; Initial Catalog=YourDatabaseName ;Persist Security Info=True;User ID=sa;Password=XXXX"

可以使用Visual Stuido中“工具“-->"连接到数据库“测试一下你的数据库是否正常

图片说明: http://i.stack.imgur.com/Om7gs.jpg

然后使用”测试连接“按钮看看是否连接成功

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