且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#代码使用Sql或Windows身份验证登录到Sql Server

更新时间:2022-10-24 18:39:02

使用当前Windows凭据的SQL连接不应提供用户名和密码,而是将连接字符串的 Integrated Security 属性设置为 SSPI ...

(也可以 true Trusted_Connection = true - 所有意思都一样)

  string  connectionString =  初始目录= MyDb;数据源= MyServer;集成安全性= SSPI; 



如果你无法使用此连接字符串连接,这意味着没有启用Windows身份验证),您可以尝试使用用户名和密码进行连接...

  string  connectionString =   初始目录= MyDb;数据源= MyServer;用户ID = [用户名];密码= [口令]跨度> 


hi,
i had a form which contains some text boxes like
1.Server Name
2.Port Number(other than 1433)
3.Database name:
4.User name(SA):
5.Password:

so in these 5 text boxes if user enters the servername, port(if any), database name, username(sql authentication), password. which these are later saved as connection string and used to login to sql server... but what happens if user doesnt login into server with sql authentication and he every day logs in with windows authentication?

i will provide a dropdown same as the sql server login screen there if user selects SQL authentication, well and good, it works fine, but if user wants to login as windows authentication. how, we have to write the code?
please help in this issue as i have to submit the project ASAP

To make an SQL connection using the current Windows credentials you should not provide username and password, but set Integrated Security property of the connection string to SSPI...
(It can be also true or Trusted_Connection=true - all means the same)
string connectionString="Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;"


If you fail to connect using this connection string it means that no Windows authentication enabled )for you or at all) and you can try and connect using username and password...

string connectionString="Initial Catalog=MyDb;Data Source=MyServer;User Id=[username]; password=[password]"