如何在数据库中进行C#编程时登录失败时解决连接问题?

时间:2016-02-25 03:15:20

标签: c# sql-server azure-sql-database

我在Windows窗体上使用Azure数据库连接数据时做了一些编码,当我尝试检索数据时,收到了以下错误:

  

System.Data.dll中发生了未处理的“System.Data.SqlClient.SqlException”类型异常。

此外,我收到Login failed for user ''.当我尝试检索数据并位于myConnection.Open();

private void btnRetrieve_Click(object sender, EventArgs e)
{
    //Create a connection calling the App.config
    string conn = ConfigurationManager.ConnectionStrings["NYPConnection"].ConnectionString;
    //The query to use
    string query = "SELECT * FROM Users";
    SqlConnection myconnection = new SqlConnection(conn);
    //Create a Data Adapter
    SqlDataAdapter dadapter = new SqlDataAdapter(query, myconnection);
    //Create the dataset
    DataSet ds = new DataSet();

    //Open the connection
    ******myconnection.Open();******

    //Fill the Data Adapter
    dadapter.Fill(ds, "Users");
    myconnection.Close();
    //Bind the datagridview with the data set
    dataGridView1.DataSource = ds;
    dataGridView1.DataMember = "Users";
}          

1 个答案:

答案 0 :(得分:1)

使用以下代码打印conn的值:

string conn = ConfigurationManager.ConnectionStrings["NYPConnection"].ConnectionString;
Debug.WriteLine("conn= " + conn);

查看输出窗口,您可能会发现conn设置为空字符串,或者可能没有指定用户名。