0

what is wrong with this code?

field="id";
table="MInvMonth";
condition="machine_id=37";
 public static String getConditionedField(String field, String table, String condition)
    try
    {
        if (cmd == null) getConnection();
        cmd.CommandText = "Select " + field + " from " + table + " where " + condition;
        SQLiteDataReader reader = cmd.ExecuteReader();
        if (reader.HasRows==true)
        {
            reader.Read();
            string s = reader[0].ToString(); // return first element
            reader.Close();
            return s;
        }
        reader.Close();
        return null;
    }
    catch (Exception e)
    {
        MessageBox.Show("Caught exception: " + e.Message+"|"+cmd.CommandText);
        return null;
    }

I checked the sql statement, it turns the right value. why can't I read it? the returnvalue is "".

3
  • Have you tried setting a breakpoint on your string s = ... line? Try to add reader[0] to watch. What does it show? reader[1]? reader[2]? Commented May 16, 2010 at 13:35
  • 1
    JUst a word of advice, the way your setting up that sql command opens up oportunities for SQL Injection, u should look at using parametrized queries:csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx Commented May 16, 2010 at 14:10
  • What is the SQL data type of field? Commented May 16, 2010 at 14:19

3 Answers 3

1

Are you sure the zero index contains the value you need? Maybe it is another column.

Sign up to request clarification or add additional context in comments.

Comments

0

Sometimes the first element is 1 not 0, did you try replacing that?

Comments

0

the first time I misstyped the sql staement. now it is good, it must return just the id field. The thing is, that this is a function and with other type of queries, when the returned field type is string, it is working fine.

I tried to debug, and the reader[0].value is empty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.