如何导入MDB文件,在SQL中读取和保存

时间:2014-02-07 12:20:13

标签: c# asp.net sql ms-access

我需要导入.MDB文件,在SQL Server中读取和保存。 我试过这个:

方法导入

protected void Btn_Importar(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
        {
            if (FileUpload1.PostedFile.ContentType == "application/msaccess")
            {
                    string filename = Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.SaveAs(Server.MapPath("~/Upload/") + filename);
                    Label1.Text = "File uploaded successfully!";
                    //ReadMdb();
                    Insert();
            }
    }
}

方法插入

public void Insert()
{
        string strFile = Server.MapPath("~/Upload/teste.mdb");
        string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFile;
        var myDataTable = new DataTable();
        using (var connection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=" + strFile))
        {
            connection.Open();
                var query = "SELECT * FROM BOLETO";
                var command = new OleDbCommand(query, connection);
                var reader = command.ExecuteReader();

                Conexaocs con = new Conexaocs();
                con.Conexao();

                SqlCommand sqlComm = new SqlCommand("INSERT INTO BOLETO (CODIGO,NF_CONTA,TEXTO) VALUES (@CODIGO, @NF_CONTA, @TEXTO)", conn);

                //if (reader.HasRows)
                //{
                //    while (reader.Read())
                //    {
                //        //ListBox1.Items.Add(reader.GetInt32(0).ToString() + " - " + reader.GetString(1));
                //    }

                for (int i = 0; i < reader.FieldCount; i++)
                {
                    sqlComm.Parameters.AddWithValue("@CODIGO", reader[i]);
                        sqlComm.Parameters.AddWithValue("@NF_CONTA", reader[i]);
                        sqlComm.Parameters.AddWithValue("@TEXTO", reader[i]);
                        sqlComm.ExecuteNonQuery();
                }

                connection.Close();
        }
}

但是,当这一点到来时不能保存!

for (int i = 0; i < reader.FieldCount; i++)
{
   sqlComm.Parameters.AddWithValue("@CODIGO", reader[i]);
   sqlComm.Parameters.AddWithValue("@NF_CONTA", reader[i]);
   sqlComm.Parameters.AddWithValue("@TEXTO", reader[i]);
   sqlComm.ExecuteNonQuery();

}

消息错误: System.InvalidOperationException:行或列没有数据 enter image description here

有些想法?谢谢

2 个答案:

答案 0 :(得分:2)

正如戈德汤普森所说,你需要遍历行,而不是字段。请尝试以下(未经测试的)代码:

if (reader.HasRows)
{
    while (reader.Read())
    {
        sqlComm.Parameters.AddWithValue("@CODIGO", reader[0]);
        sqlComm.Parameters.AddWithValue("@NF_CONTA", reader[1]);
        sqlComm.Parameters.AddWithValue("@TEXTO", reader[2]);
        sqlComm.ExecuteNonQuery();
    }
}

答案 1 :(得分:1)

  

Nãoexistemdados para a linha ou coluna

显然意味着

  

行或列没有数据

您打开了OleDbDataReader,但没有Read()。 (你曾经做过一次,但while循环被注释掉了。)