这是我从文本文件到mysql数据库
的结果我希望它是
Product_Name Product_Price QTY
Pepsi 30 64
Coke 35 24
Sandwich 60 14
这是代码。
try
{
var files = from file in Directory.EnumerateFiles(@"C:\Users\K\Desktop\New folder", "*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
using (StreamReader sr = new StreamReader(f.File))
{
foreach (string line in File.ReadAllLines(f.File).SkipWhile(x => !x.Contains("[Start]")))
{
string readLine;
do
{
readLine = sr.ReadLine();
string[] readLineSplit = readLine.Split('|');
if(readLineSplit.Length > 1)
{
using (MySqlConnection con = new MySqlConnection(@"server=localhost;database=test;uid=root;pwd=pw;"))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Products(Product_Name, Product_Price, QTY) VALUES (@Product_Name, @Product_Price, @QTY)", con);
cmd.Parameters.AddWithValue("@Product_Name", readLineSplit[0].ToString());
cmd.Parameters.AddWithValue("@Product_Price", readLineSplit[1].ToString());
cmd.Parameters.AddWithValue("@QTY", readLineSplit[2]);
cmd.ExecuteNonQuery();
}
}
} while (!sr.EndOfStream);
}
问题2:我的路径中有两个文本文件,知道为什么只有一个文本文件插入到我的数据库中?
答案 0 :(得分:2)
要问题1,请删除引号,将不必要的ToString()
替换为Trim('\"')
:
//readLineSplit[0].ToString()
readLineSplit[0].Trim('\"')
答案 1 :(得分:0)
我不知道你的文件内容是怎样的,但是你不能只用“替换?”来替换“符号吗?
readLineSplit[0].ToString().Replace("\"", "");