我的计划的步骤是:
我的问题:
代码有几个部分。我将粘贴主要的:
呼叫:
string id_file = Get_id_file(filenameout, id_costumer);
//MessageBox.Show("the id of the file will be: " + id_file);
DataTable csvFileData = GetDataTabletFromCSVFile(filenameout, id_file);
InsertDataIntoSQLServerUsingSQLBulkCopy(csvFileData, destinytablename);
从DB读取:
public static string Get_id_file(string filenameout,string id_id_costumer)
{
var fileName = Path.GetFileNameWithoutExtension(filenameout);
string return_id_file = "";
using (SqlConnection dbConnection = new SqlConnection("XXXXX"))
{
try
{
dbConnection.Open();
SqlDataReader myReader = null;
// Using the DB to find the value
SqlCommand myCommand = new SqlCommand("select ID from TB_FILE_NAMES where path_name='" + fileName + "' and id_program='" + id_id_costumer + "'",
dbConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
MessageBox.Show("the ID selected for the file is: " + myReader["ID"].ToString());
return_id_file = (myReader["ID"].ToString());
}
//return_id_file = "9999";
return return_id_file;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return ("Error in return_id_file");
}
} // end of using (SqlConnection dbConnection)
}
“GetDataTableFromCSVFile”的一部分 在这一部分,我只想将ID(在上一步中找到)设置为该特定CSV的所有行
// Add a column with the ID of the file
//DataColumn Col =
csvData.Columns.Add("ID_TB_FILE_NAMES", System.Type.GetType("System.String"));
// Set a value for the entire column - ID of the File
//var column2 = csvData.Columns["ID_TB_FILE_NAMES"];
foreach (DataRow row in csvData.Rows)
{
//row.SetField(id_file_name, column2);
row.SetField("ID_TB_FILE_NAMES", id_file_name);
}
return csvData;
} // end of GetDataTabletFromCSVFile
在DB上编写csvData:
static void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData,string destinytablename)
{
using (SqlConnection dbConnection = new SqlConnection("XXXXX"))
{
dbConnection.Open();
// Clean the destiny table
//string query = "TRUNCATE TABLE " + destinytablename;
//SqlCommand cmd = new SqlCommand(query, dbConnection);
//cmd.ExecuteNonQuery();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = destinytablename;
//foreach (var column in csvFileData.Columns)
// s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(csvFileData);
}
}
} // end of InsertDataIntoSQLServerUsingSQLBulkCopy
我花了3天时间试图找出......欢迎任何帮助。
谢谢。