user1238784
user1238784

Reputation: 2440

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();

Upvotes: 0

Views: 123

Answers (1)

Mirko Acimovic
Mirko Acimovic

Reputation: 506

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();
         }
    }

Upvotes: 2

Related Questions