使用C#将数组的多个值插入mysql [英] Inserting multiple values of an array to mysql using c#

查看:75
本文介绍了使用C#将数组的多个值插入mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

在我的应用程序中,我从数组中的目录中存储了文件列表.我想将具有单独ID,名称和路径的文件存储在mysql数据库中.如何将这些文件分别存储在mysql中?

我的代码是:

字符串[]文件= Directory.GetFiles(@"C:\ Temp \","*.wav");

请帮帮我.

在此先感谢.

Hi all,

In my application i stored list of files from a directory in an array. I want to store that files with seperate id, name and path in mysql database. How to store that files individually in mysql?

My code is:

string [] files = Directory.GetFiles(@"C:\Temp\","*.wav");

Please help me.

Thanks in advance.

推荐答案

INSERT语句可以一次在MsSQl和MySql中提供多行:
The INSERT statement can provide multiple rows at a time, in both MsSQl and MySql:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...) (nextValue1, nextValue2, ...)

因此,在这种情况下,您可以汇编将插入许多行的命令字符串-通常我不建议这样做,因为您应该使用参数化查询来避免SQL注入攻击.在这种情况下,您可能应该检查名称和路径以确保它们不包含SQL!

使用StringBuilder,并在循环中组装SQL:

So in this case you can assemble a command string which will insert many rows - normally I would not recommend this, as you should use parametrised queries to avoid SQL Injection attacks. In this case, you should probably check names and paths to make sure they do not contain SQL!

Use a StringBuilder, and assemble SQL in a loop:

StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO myTable (filename, path) VALUES ");
foreach (string file in files)
    {
    string path = ...;
    string name = ...;
    sb.AppendFormat("('{0}', '{1}') ", name, path);
    }
string sqlCommand = sb.ToString();

然后,您要做的就是将文件分为名称和路径.如果已将数据库设置为对索引使用身份字段,它将为您处理.

Then all you have to do is break the file into the name and path. If you have set your DB to use an Identity field for the Index, it will handle that for you.


解决方案1概述了解决方案,此外您可能考虑使用SqlParameter.而不是传递硬编码的Sql字符串.您可能会看到此链接
配置参数和参数数据类型 [
As Solution 1 outline the solution, in addition to that you might consider to use SqlParameter instead of passing hard coded Sql string. You might see this link
Configuring Parameters and Parameter Data Types[^] to see usage of the SqlParameter.

Hope it helps :)


这篇关于使用C#将数组的多个值插入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆