0
這裏是我的代碼:閱讀從文本文件中的行線並保存到數據庫
List<string> myValues = new List<string>();
string line;
StreamReader file = new StreamReader(@"D:\a.txt");
if ((line = file.ReadLine()) != null)
{
string[] fields = line.Split(',');
using (SqlConnection con = new SqlConnection(@"Data Source=NT;Initial Catalog=SinhVien;Integrated Security=True"))
{
con.Open();
while((line = file.ReadLine()) != null)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Sinhvien(ID, HoTen, DiaChi) VALUES (@id, @hoten, @diachi)", con);
cmd.Parameters.AddWithValue("@id", fields[0].ToString());
cmd.Parameters.AddWithValue("@hoten", fields[1].ToString());
cmd.Parameters.AddWithValue("@diachi", fields[2].ToString());
cmd.ExecuteNonQuery();
}
}
}
我的文本文件:
10,Hong,10 hung vuong
11,Thuy,11 Hung Vuong
22,Thanh,22 Hung Vuong
但我不能保存所有行的數據庫?
你是從第二行開始的,是你想要的嗎?你也一次只拆分一次字段而不是每行(將其移入循環中)。 –
哪些行不能保存到數據庫?他們只是沒有出現在那裏,或者你有錯誤嗎?問題現在還不太清楚。 – DavidG
我猜你正在保存相同的數據2次? – Jonesopolis