Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query from C#

Tags:

c#

sql

I am trying to query SQL Server database from C#

I have class

Class_A 
{
  public fetch((string name, string last_name))
  {
    SqlConnection conn = null;
    double val = 0;
    string server = "123.444.22.sss";
    string dbase = "xyz";
    string userid = "cnsk";
    string password = "xxxxxx";
    string connection = "Data Source=" + server + ";Initial Catalog=" + dbase 
                        + ";User ID=" + userid + ";Password=" + password;

    conn = new SqlConnection(connection);

    try
    {
      conn.Open();
    }
    catch(Exception)
    {
      string e = "Database error contact administrator";
      MessageBox.Show(e, "Error!");
    }
    try
    {
      SqlDataReader myReader = null;
      SqlCommand myCommand = new SqlCommand("select * from table where NAME"
         + " = name and LAST_NAME = last_name", conn);
      myReader = myCommand.ExecuteReader();
      while (myReader.Read())
      {
        //do something

      }
    }
    catch (Exception e)
    {
      Console.WriteLine(e.ToString());
    }
    return (0);
  }
}

There is a problem in my query.

When I give normal query "select * from table" --- this gives me perfect results.

But when I try to give where condition it gives me error. Any suggestions, to fix this? Thanks.

like image 804
Csharp_learner Avatar asked Apr 01 '12 17:04

Csharp_learner


1 Answers

Use a parameterised query, and more usings, and stop with the generic exceptions.

something like this where somName and SomeLastName are the values that you wan t to query for.

String sql = "Select * From SomeTable Where [Name] = @Name and [Last_Name] = @LastName";
try
{
  using(SqlConnection conn = new SqlConnection(connection))
  {
    conn.Open();
    using( SqlCommand command = new SqlCommand(sql,conn))
    {
      command.Parameters.Add(new SqlParameter("Name", DbType.String,someName));
      command.Parameters.Add(new SqlParameter("LastName", DbType.String,someLastName));
      using(IDataReader myReader = command.ExecuteReader())
      {
        while (myReader.Read())
        {
           //do something
        }
      }
    }
  } 
  return 0; // Huh?
}
catch(SqlException sex)
{
   Console.Writeline(String.Format("Error - {0}\r\n{1}",sex.Message, sex.StackTace))
}

NB not checked might be a silly in it

like image 64
Tony Hopkinson Avatar answered Oct 13 '22 00:10

Tony Hopkinson