I've written some code to check whether a given subject name exists in my SQL database. Please see below:
string exists = String.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int j = 0; j < reader.FieldCount; j++)
{
exists = reader.GetValue(j) + "";
}
}
}
}
}
note: connectionString has already been declared above in my program
I am using this code in a few methods and don't want to have duplicated code, therefore I am thinking of making this into a method.
Problem lies in that the next piece of code in my methods in which i use the above code uses the exists
string and checks whether or not it is empty.
Pseudo code below:
if(String.ISNullOrEmpty(exists))
{
//do some code
}
else
{
//do some code
}
I have made the method as follows:
private static string SubjectExistsChecker(string input, string exists)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int j = 0; j < reader.FieldCount; j++)
{
exists = reader.GetValue(j) + "";
}
}
}
}
return exists;
}
}
I then call the method as follows:
MethodName()
{
//some code asking for subjectName which we call `input`
String exists = string.Empty;
SubjectExistsChecker(input, exists);
if (string.IsNullOrEmpty(exists))
{
//do some code
}
else
{
//do some code
}
When writing the code out fully (not using method) as shown at the top, this works.
Now that I've made the method, it doesn't work and exists
stays null.
Can anyone help? Where am I going wrong? I'm guessing its something to do with the exists
string.