【问题标题】:inserting an array into sql server and mysql database using c# .net使用 c# .net 将数组插入 sql server 和 mysql 数据库
【发布时间】:2011-06-17 06:38:35
【问题描述】:

我的 Winforms 应用程序有一个 C# 列表:

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

我已将这些插入到列表中:

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

现在我有一张桌子:STUDENTS

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

我应该为 MySql 使用 implode 函数吗?但是语法是什么?还有,要为 SQL Server 做什么。

我在做:

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

但是有一些错误。请帮忙。

【问题讨论】:

    标签: c# .net mysql sql-server arrays


    【解决方案1】:

    这应该可以解决您的查询

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

    但是,您最好使用参数化查询,而不是字符串连接。

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

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

    【讨论】:

    • @Alex Aza : 先生,您能帮我提供参数化查询代码吗?
    • @Alex Aza:先生,这对 Mysql 和 SQL Server 都有效吗?
    • 非常感谢先生,另外,如果我使用 Implode 函数,它会起作用吗?我有一台 Linux 服务器,PHP 也有。
    • @Alex Aza :另外,我如何从表中只读取特定主题的名称?就像我只想查看选择了英语的学生一样,那么查询是什么? -- 从 SubjectsSelected = 'English' 的学生中选择 *,那么它会起作用吗?
    • @Alex Aza : 或者是这样 : select * from students where SubjectsSelected LIKE %English%
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多