Connect to AS400 using .NET

前端 未结 7 2154
再見小時候
再見小時候 2020-12-12 19:39

I am trying to build a .NET web application using SQL to query AS400 database. This is my first time encountering the AS400.

What do I have to install on my machine

7条回答
  •  遥遥无期
    2020-12-12 20:02

    As mentioned in other answers, if you have the IBM i Access client already installed, you can use the IBM.Data.DB2.iSeries package.

    If you don't have the IBM i Access software, you can leverage JTOpen and use the Java drivers. You'll need the nuget package JT400.78 which will pull in the IKVM Runtime.

    In my case I needed to query a DB2 database on an AS400 and output a DataTable. I found several hints and small snippets of code but nothing comprehensive so I wanted to share what I was able to build up in case it helps someone else:

    using com.ibm.as400.access;
    using java.sql;
    
    var sql = "SELECT * FROM FOO WITH UR";
    
    DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
    Connection conn = DriverManager.getConnection(
        "jdbc:as400:" + ServerName + ";prompt=false", UserName, Password);
    
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    ResultSetMetaData md = rs.getMetaData();
    int ct = md.getColumnCount();
    
    DataTable dt = new DataTable();
    for(int i=1; i<=ct; i++)
        dt.Columns.Add(md.getColumnName(i));
    
    while (rs.next())
    {
        var dr = dt.NewRow();
        for (int i = 1; i <= ct; i++)
            dr[i - 1] = rs.getObject(i);
        dt.Rows.Add(dr);
    }
    rs.close();
    

    The conversion from RecordSet to DataTable is a little clunky and gave me bad flashbacks to my VBScript days. Performance likely isn't blinding fast, but it works.

提交回复
热议问题