ODBC连接从Excel(xlsx)批量复制记录到Sybase Adaptive Server Enterprise?

时间:2019-04-02 12:53:41

标签: odbc sybase bulk

由于它是Adaptive Server Enterprise,因此SqlConnection不起作用,因此我不得不使用其他内容,例如OdbcConnection,否则(如果有建议)。

sybase数据库表(让我们说表 Customer )具有数百万条记录,并且每次运行该程序时,我都打算再推送数千条记录。记录从excel到Sybase表 Customer 。由于数量原因,我必须使用批量复制代码。假设数据库表中已经有数百万条记录,并且excel文件中还有10,000条记录,那么我不能一一遍历excel记录,所以请批量复制代码。

我需要考虑的另一件事是:Sybase表可能已经在excel文件中包含一些记录,因此我不能只使用SQL Insert Into 语句,因为Sybase中已经存在记录表Customer中,我可能需要使用SQL Update 语句。 excel文件中有一些可能的错误记录(Sybase表不会接受),我还需要使用 Try Catch 语句来捕获那些异常。

如何尝试使用我的代码将记录从Excel(xlsx)批量复制到Sybase Adaptive Server Enterprise?

谢谢。

背景:对于C#来说还很新,还没有完成代码,还没有编译代码。

private void importExcelStripMenuItem_Click(object sender, EventArgs e)
{

    var filePath = string.Empty;
    OpenFileDialog OpenFile = new OpenFileDialog();

    OpenFile.Filter = "Excel Files|*.xl*"; //Filter for excel file
    OpenFile.Title = "Select your file";
    OpenFile.FilterIndex = 2;  
    OpenFile.RestoreDirectory = true;

    if (OpenFile.ShowDialog() == DialogResult.OK)
    {
        //Get the path of specified file
        filePath = OpenFile.FileName;
    }



    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];  //Only one sheet in the workbook





    // SET A CONNECTION WITH THE EXCEL FILE.
    OdbcConnection myExcelConn = new OdbcConnection("Driver={Microsoft Excel Driver (*.xls)}; DBQ=" + filePath +"; DriverID=790");

    try
    {
        myExcelConn.Open();

        // GET DATA FROM EXCEL SHEET.
        //Select all fields from the excel file, but prefer not to use SELECT * FROM ...., due to there may be irrevalent data in other columns, I only copy first 6 columns, Sybase table Customer has only those 6 fields too.
        OdbcCommand ObjCmd = new OdbcCommand("SELECT SocialSecurityNumber, FirstName, LastName, Gender, DOB, PhoneNumber FROM [" + xlWorksheet.Name + "$]", myExcelConn);

        // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
        OdbcDataReader objBulkReader = null;
        objBulkReader = ObjCmd.ExecuteReader();



        //Close Excel file
        xlWorkbook.Close(false);
        xlApp.Quit();


        // SET THE CONNECTION STRING.


        using (OdbcConnection con = new OdbcConnection("Sybase ASE Connection String"))
        {
            con.Open();

            // FINALLY, LOAD DATA INTO THE DATABASE TABLE.
            //I don't know how to write this portion of code.
        }

        MessageBox.Show("Successfully Loaded.");

    }


    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);

    }

    finally
    {
            // CLEAR.
            //Clear other objects happened during bulk copy
            myExcelConn.Close();
            myExcelConn = null;
    }
}

期望:完成代码,将能够从Excel导入(大容量复制)记录到Sybase表中。

0 个答案:

没有答案