我通过c#读取文件,文件的格式是这个。
输入文件
00001740, 0.125, 0, able
00001740, 0.125, 0, unable
00002098, 0, 0.75, country
00002312, 0, 0, love
我想在MYSQL数据库中使用此文件。我编写的代码存储每个数据库的ROW中的每一行。但是下面的代码只写了文本文件的第一行
private void button1_Click(object sender, EventArgs e)
{
string MyConString = "server=localhost;" +
"database=zahid;" + "password=zia;" +
"User Id=root;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
connection.Open();
StreamReader reader = new StreamReader("D:\\out.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(',');
command.CommandText = "insert into score(POS_ID,Pos,Neg,Word) values('" + parts[1] + "','" + parts[2] + "','" + parts[3] + "','" + parts[4] + "')";
Reader = command.ExecuteReader();
}
}
此代码仅返回第一行,但我希望所有文本文件行都存储在数据库中。提前谢谢
答案 0 :(得分:4)
尝试清理混乱:
private void button1_Click(object sender, EventArgs e)
{
string[] lines = File.ReadAllLines("D:\\out.txt");
foreach (var line in lines)
{
var data = line.Split(new[] { ',' }, 4);
int posId = int.Parse(data[0].Trim());
double pos = double.Parse(data[1].Trim());
double neg = double.Parse(data[2].Trim());
string word = data[3].Trim();
StoreRecord(posId, pos, neg, word);
}
}
private void StoreRecord(int posId, double pos, double neg, string word)
{
var conStr = "server=localhost; database=zahid; password=zia; User Id=root;";
using (var connection = new MySqlConnection(conStr))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText =
@"INSERT INTO score
(POS_ID, Pos, Neg, Word)
VALUES
(@posId, @pos, @neg, @word)";
command.Parameters.AddWithValue("@posId", posId);
command.Parameters.AddWithValue("@pos", pos);
command.Parameters.AddWithValue("@neg", neg);
command.Parameters.AddWithValue("@word", word);
command.ExecuteNonQuery();
}
}
需要注意的事项:
using
statemenets来正确处理IDisisableable资源,例如连接和命令此外,您可能不希望rolling your own CSV parser
使用String.Split
,而是使用真正的CSV解析器。
如果CSV文件很大,您可以一次读取一行,以避免一次将其加载到内存中:
private void button1_Click(object sender, EventArgs e)
{
using (var stream = File.OpenRead("D:\\out.txt"))
using (var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
var data = line.Split(new[] { ',' }, 4);
int posId = int.Parse(data[0].Trim());
double pos = double.Parse(data[1].Trim());
double neg = double.Parse(data[2].Trim());
string word = data[3].Trim();
StoreRecord(posId, pos, neg, word);
}
}
}