Login failed for user 'sa'. in connection string

早过忘川 提交于 2019-12-29 09:06:21

问题


I'm getting the following error:

Login failed for user 'sa'

When I try to connect server by setting value through a string variable:

private SqlConnection getDbConnection = new SqlConnection("Data Source="+dbname+";Initial Catalog="+catname+";User Id=sa;Password=sa;Integrated Security=false");

But when I use the normal connection string with no string variable it works well:

private SqlConnection getDbConnection = new SqlConnection("Data Source=Ali-pc\\;Initial Catalog=master;User Id=sa;Password=sa;Integrated Security=false");

回答1:


put your connectionstring in web.config file as I show below

<connectionStrings>
<add name="Test" connectionString="data source=Harsh; Initial Catalog=Test ; user Id=sa; password=sa123;"/>
</connectionStrings>

Above "Test" is connectionstringname,you can write your datasource name.Mine is Harsh,so changed it according to yours.Give your database name in inital catalog.

And then put this code in your code behind page load event

SqlConnection con = new  SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ToString());

It will work.




回答2:


Maybe the server name and the database name (in the dbname and catname variables) are just wrong?

BTW, i would recommend using the SqlConnectionStringBuilder class.

var sb = new SqlConnectionStringBuilder() { InitialCatalog = catname,
                                            DataSource = dbname,
                                            UserID = "sa",
                                            Password = "sa" };

var dbConnection = new SqlConnection(sb.ConnectionString);


来源:https://stackoverflow.com/questions/9636511/login-failed-for-user-sa-in-connection-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!