如何使用C#代码使用Sql或Windows身份验证登录到Sql Server [英] How Do I Login To Sql Server Using Either Sql Or Windows Authentication Using C# Code

查看:840
本文介绍了如何使用C#代码使用Sql或Windows身份验证登录到Sql Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i的表格中包含一些文字框,如

1.服务器名称

2.Port编号(1433除外) )

3.数据库名称:

4.用户名(SA):

5.Password:



所以在这5个文本框中,如果用户输入servername,port(如果有),数据库名称,用户名(sql身份验证),密码。这些后来保存为连接字符串并用于登录到sql server ...但是如果用户没有使用sql身份验证登录到服务器并且他每天都使用Windows身份验证登录会发生什么?



i将提供与sql server登录界面相同的下拉菜单,如果用户选择SQL身份验证,那么好,它工作正常,但如果用户想要以Windows身份登录认证。如何,我们必须编写代码?

请帮助解决这个问题,因为我必须提交项目ASAP

解决方案

使用当前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]"


这篇关于如何使用C#代码使用Sql或Windows身份验证登录到Sql Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆