Using a SQL parameter
It execute the query to filter on the word to search and returns all available synonyms 0..*
using the generic List class to store values that will be joined for a one line display in the text box (empty string if none found):
using System.Collections.Generic;
var synonyms = new List<string>();
using ( var connection = new SqlConnection(connectionString) )
try
{
connection.Open();
using ( var command = connection.CreateCommand() )
{
command.CommandText = "SELECT Synonym FROM [Ant&Syn] WHERE Word = ?";
command.Parameters.Add("@word", SqlDbType.Text).Value = TextBox1.text;
using ( var reader = command.ExecuteReader() )
while ( reader.Read() )
synonyms.Add(reader[0].ToString());
}
}
finally
{
connection.Close();
}
TextBox2.Text = string.Join(", ", synonyms);
We can manage multiple results with a multi-line textbox, a listbox, a context menu or anything else.
What are good ways to prevent SQL injection?
AddWithValue sql injection safe? Why?
SqlCommand Parameters Add vs. AddWithValue
Output
Fine
Improvement - Refactoring
We can create a method and use the yield keyword to return a IEnumerable:
IEnumerable<string> GetSynonyms(string word)
{
using ( var connection = new SqlConnection(connectionString) )
try
{
connection.Open();
using ( var command = connection.CreateCommand() )
{
command.CommandText = "SELECT Synonym FROM [Ant&Syn] WHERE Word = ?";
command.Parameters.Add("@word", SqlDbType.Text).Value = word;
using ( var reader = command.ExecuteReader() )
while ( reader.Read() )
yield return reader[0].ToString();
}
}
finally
{
connection.Close();
}
}
var synonyms = GetSynonyms(TextBox1.text);
Improvement - Case insensitive comparison
We can use a flag to set the option:
IEnumerable<string> GetSynonyms(string word, bool caseInsensitive)
{
using ( var connection = new SqlConnection(connectionString) )
try
{
connection.Open();
using ( var command = connection.CreateCommand() )
{
string checkColumn = caseInsensitive ? "lower(Word)" : "Word";
string checkMatch = caseInsensitive ? word.ToLower() : word;
command.CommandText = "SELECT Synonym FROM [Ant&Syn] WHERE " + checkColumn + " = ?";
command.Parameters.Add("@word", DbType.String).Value = checkMatch;
using ( var reader = command.ExecuteReader() )
while ( reader.Read() )
yield return reader[0].ToString();
}
}
finally
{
connection.Close();
}
}