简体   繁体   中英

SQL Server cannot build connection string to db

I tried the following in SQL Server Management Studio; I can connect and run query, but not from my project

string s = "Server=LAPTOP-7J47C5JA\SQLEXPRESS;Database=Test;Trusted_Connection=True;";

string queryString =   "SELECT * from tbclienti";

cn = new SQLConnection(s);

// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);

cn.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    Text = reader[0].ToString();
    label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}

reader.Close();
cn.Close();

I posted here whole code what could look like. Try it now.

    string s = @"Server=(local)\SQLEXPRESS;Database=Test;Integrated Security=SSPI;";

    using(SqlConnection cn = new SqlConnection(s))
    {
        string queryString = "SELECT * from tbclienti";

        try
        {    
          cn.Open();
          // Create the Command and Parameter objects.
          SqlCommand command = new SqlCommand(queryString, cn);
          SqlDataReader reader = command.ExecuteReader();
          while (reader.Read())
          {
             Text = reader[0].ToString();
             label1.Text = reader[1].ToString()+ " " + reader[2].ToString();

           }
           reader.Close();
         }
         catch(Exception ex) 
         {
             // see if error appear
         }
         finally
         {
           cn.Close();
         }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM