我正在开发一种数据库迁移工具。我的编程教育公司正在完全改写那里的数据库,并且我正在构建一个可以导入CSV的应用程序,只获取我们需要的重要数据,然后将其分散到数据库中。我想使其尽可能可重用,而不必在每次导入新的CSV时都为每种数据类型创建新的对象。我正在将其(我已经拥有的)移到Windows窗体应用程序中,该应用程序让我导入CSV文件,然后依次列出属性,然后单击按钮进行处理,然后有了数据库包含相关信息的表格。
如果您对完成此操作有任何建议,请告诉我。
static void Main(string[] args)
{
var count = 0;
using(var reader = new StreamReader(@"C:\Users\Tim\Documents\FullData.csv"))
{
while (!reader.EndOfStream)
{
var str = reader.ReadLine();
count = count + 1;
var IndividualProperties = str.Split(',');
StudentEntity StudentData = new StudentEntity()
{
Id = count,
FirstName = IndividualProperties[1],
LastName = IndividualProperties[0],
Email = IndividualProperties[2],
PhoneNumber = IndividualProperties[3],
Address = IndividualProperties[4],
City = IndividualProperties[5],
Gender = IndividualProperties[8]
};
AddUserToDb(StudentData, "StudentData");
Console.WriteLine(str);
}
}
Console.WriteLine("Total Students Saved: " + count);
}
static void AddUserToDb(StudentEntity Object, string DatabaseName)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
var commandString = "INSERT INTO " + DatabaseName + "(FirstName,LastName,Email,PhoneNumber,Address,City,Gender,Id) VALUES(@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8)";
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(commandString, connection))
{
command.Parameters.Add("@p1", SqlDbType.Text).Value = Object.FirstName;
command.Parameters.Add("@p2", SqlDbType.Text).Value = Object.LastName;
command.Parameters.Add("@p3", SqlDbType.Text).Value = Object.Email;
command.Parameters.Add("@p4", SqlDbType.Text).Value = Object.PhoneNumber;
command.Parameters.Add("@p5", SqlDbType.Text).Value = Object.Address;
command.Parameters.Add("@p6", SqlDbType.Text).Value = Object.City;
command.Parameters.Add("@p7", SqlDbType.Text).Value = Object.Gender;
command.Parameters.Add("@p8", SqlDbType.Int).Value = Object.Id;
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Something went wrong");
}
}
}