1

I have a List in C# for my Winforms application:

List<string> StudentSubjects = new List<>(string);

I have inserted these into List :

 StudentSubjects.Add("Physics", "Chemistry", "Mathematics", "English");

Now i have a table: STUDENTS

----------
**StudentID     | SubjectsSelected**
---------
STDNT001        |  [HERE all subjects selected by the student should be inserted]     
STDNT002        |  Physics, Chemistry, Mathematics, English
STDNT002        |  Physics, Chemistry, Mathematics, English
----------

Shall i use the implode function for MySql? But what's the syntax? Also , what to do for SQL Server.

I am doing:

string query =
"INSERT INTO STUDENTS VALUES 
('S001', implode('" + StudentSubjects.ToArray() + " ')) "

But there's some error. Please help.

1 Answer 1

2

This should fix your query

string query = @"
    INSERT INTO STUDENTS VALUES 
    ('S001', '" + string.Join(",", StudentSubjects) + "')";

However, you better use parametrized query, instead of string concatenation.

For MySQL:

using (var connection = new MySqlConnection(connectionString))
using (var command = connection.CreateCommand())
{
    command.CommandText = @"
        INSERT INTO STUDENTS VALUES 
        ('S001', ?subjects)";
    var param = command.Parameters.Add("?subjects", MySqlDbType.VarChar);
    param.Value = string.Join(",", StudentSubjects);
    connection.Open();
    command.ExecuteNonQuery();
} 

For SQL Server:

using (var connection = new SqlConnection(connectionString))
using (var command = connection.CreateCommand())
{
    command.CommandText = @"
        INSERT INTO STUDENTS VALUES 
        ('S001', @subjects)";
    command.Parameters.AddWithValue("subjects", string.Join(",", StudentSubjects))
    connection.Open();
    command.ExecuteNonQuery();
}
Sign up to request clarification or add additional context in comments.

6 Comments

@Alex Aza : sir, can you please help me with the parameterized query code also.
@Alex Aza : sir,is this valid for both : Mysql as well as SQL Server?
thanks a lot sir, also, if i use Implode function , then will it work? I have a Linux server , so have PHP.
@Alex Aza : also, how would i read only particular subjects name from the table? like if i only want to view students who have opted for English, then what would be the query? -- select * from students where SubjectsSelected = 'English', then will it work?
@Alex Aza : or it would be this : select * from students where SubjectsSelected LIKE %English%
|

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.