0

I'm making this program which tells me the antonym of inserted word. Basically, I have a textBox and a button. Text from textbox is being searched for a match from database and i want to return the column next to it, containing the antonym of a given word. Here's the code:

 private void btnFind_Click(object sender, EventArgs e)
{
    OleDbCommand command1 = new OleDbCommand();
    command1.Connection = connection;
    command1.CommandText = "select * from antonymsdb where '" + txtWord.Text + "' = word";
    OleDbDataReader reader = command1.ExecuteReader();
    int count = 0;
    while (reader.Read())
    {
        count++;
    }
    if (count == 1)
    {
        //word has been found and i want to take the word from the column next to this one and put it in a variable
    }
}

word is a column of the antonymsdb database from Access.

YowE3K
  • 23,852
  • 7
  • 26
  • 40

1 Answers1

0

If you are getting a single value (antonym) then do not use a reader. Just use the ExecuteScalar method:

OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
command1.CommandText = 
   "select nameOfColumn from antonymsdb where word ='" + txtWord.Text + "'";
string antonym = command1.ExecuteScalar().ToString();  
connection.Close();

If you are expecting more than one then do this:

var antonyms = new List<string>();
while (reader.Read())
{
    antonyms.Add(reader.GetString(putIndexOfColumnHere));
}

Also make sure you read this because your code is open to sql injections.

Community
  • 1
  • 1
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • Doesn't really work. I don't know if I explained well. So far, I have code that searches database and finds the word. I just don't know how to take the word with the same ID, primary key, same row, just column called antonym, not word.. – Stevan Marjanović May 20 '17 at 23:39
  • See my edit. You need to fix your query. Make sure to put the names of your columns in my query because I do not know the names of your columns. – CodingYoshi May 20 '17 at 23:53