我正在尝试构建一个应用程序,它将使用SQL将txt文件加载到数据库中。我在SQL方面很擅长,但让C#工作起来很困难。我按下按钮运行此命令。我想将解析后的数据放入数据库,我将在SQL中修改它。
我目前停留在“索引超出数组范围”错误,我在第command.Parameters["@num2"].Value = items[1];
行收到
数据如下所示:
SECURITIES|ERROR CODE|NUM FLDS|PX_LAST|
ASWABUND Curncy|0|1|44.665000|
BCOMTR Index|0|1|162.554200|
BP0001M Index|0|1|.251630|
BP0002M Index|0|1|.270380|
BP0003M Index|0|1|.296810|
BP0006M Index|0|1|.438130|
...etc....
我的代码就是这样:
using (SqlConnection connection = new SqlConnection("Server=LAPTOP-LLSEHUPE;Integrated Security = SSPI;"
+ "database=tempdb"))
{
string sqlscript1 = "CREATE TABLE ##Temp_BBG_Daily " +
"( [Temp_Ticker] Varchar(max) NULL, " +
" [Temp_Field2] int NULL, " +
" [Temp_Field3] int NULL, " +
" [Temp_Value] Varchar(max) NULL) ";
SqlCommand command = new SqlCommand(sqlscript1, connection);
connection.Open();
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO ##Temp_BBG_Daily ([Temp_Ticker],[Temp_Field2]," +
"[Temp_Field3],[Temp_Value]) " +
"VALUES (@num1, @num2, @num3, @num4)";
command.Parameters.Add("@num1", SqlDbType.VarChar);
command.Parameters.Add("@num2", SqlDbType.Int);
command.Parameters.Add("@num3", SqlDbType.Int);
command.Parameters.Add("@num4", SqlDbType.VarChar);
string[] allLines = File.ReadAllLines("D:\\WORK\\Project\\NNL_PH_SNAP1800.20170620 - Copy.txt");
{
for (int i = 1; i < allLines.Length; i++)
{
string[] items = allLines[i].Split(new char[] {'|'});
command.Parameters["@num1"].Value = items[0];
command.Parameters["@num2"].Value = items[1];
command.Parameters["@num3"].Value = items[2];
command.Parameters["@num4"].Value = items[3];
command.ExecuteNonQuery();
}
}
}