我需要使用什么SQL连接字符串才能使用Windows身份验证或SQL身份验证访问localhost\SQLEXPRESS?

20
我在计算机上安装了SQL Express以便练习创建表并进行修改。我在Visual Studio中编写了一个网页,基本上是从SQLEXPRESS的表中选择*,但我无法使连接字符串起作用。请帮忙。
我的连接字符串如下:
"Data Source = localhost \ SQLEXPRESS; Initial Catalog = test; User Id = xaa9-PC \ xaa9; Password = abcd;"
错误消息:
查询为select * from tblCustomers where username='johndoe' error is Login failed for user 'x309-PC\x309'。
描述:执行当前Web请求时发生未处理的异常。请查看堆栈跟踪以获取有关错误和代码源的更多信息。
例外详细信息:System.Exception: 查询为select * from tblCustomers where username='johndoe' error is Login failed for user 'x309-PC\x309'。

4
请访问 ConnectionStrings.com,它展示了所有已知的SQL Server连接字符串的可能组合和变化,方便易懂。 - marc_s
4个回答

62

尝试使用 Windows 认证:

Data Source=localhost\SQLEXPRESS;Initial Catalog=test;Integrated Security=SSPI;

8
尝试这样做:

像这样尝试:

string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=test;User Id=x309;Password=abcd;";

还要确保您已经启用了SQL身份验证


1
这是一个Windows DOMAIN\USERNAME,因此SQL身份验证不可行,您需要使用集成身份验证。 - Ben
@Ben,使用Windows身份验证时,您不需要在连接字符串中指定用户名和密码。 - Darin Dimitrov
@Andomar,我认为连接字符串中的\x存在问题,因为它被视为十六进制。 - Darin Dimitrov
@Darin Dimitrov:看起来反斜杠不是 SQL Server 登录名中允许的字符。所以他可能正在尝试使用 Windows 身份验证登录,而他的 PC 名称为 xaa9-PC - Andomar
@Andomar,那么为什么错误信息中提到了“x309-PC”? - Darin Dimitrov
显示剩余3条评论

0
如果您将数据连接字符串放置在web.config文件中,您可以像下面这样指定您的连接:
<connectionStrings>
<add name="NorthwindConnString" 
     connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" 
     providerName="System.Data.SqlClient"/>
</connectionStrings>

但是,如果您在基于C#的网站中进行硬编码,则必须转义'\'反斜杠:

"Data Source=.\\\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"

即使是 Scott Hanselman 也可能会忘记 this...


0
public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=SHANU-PC\SQLEXPRESS;Initial Catalog=Anusha;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {

        con.Open();
        SqlCommand cmd=new SqlCommand("select * from tbl_state",con);

        SqlDataAdapter da=new SqlDataAdapter(cmd);

        DataTable dt=new DataTable();
        da.Fill(dt);
            DropDownList1.DataSource = dt;
            DropDownList1.DataTextField = "sname";
            DropDownList1.DataValueField = "sid";
            DropDownList1.DataBind();

        con.Close();
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接