开发者

inserting an array into sql server and mysql database using c# .net

开发者 https://www.devze.com 2023-03-13 19:40 出处:网络
I have a List in C# for my Winforms application: List<string> StudentSubjects = new List<>(string);

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.


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消