使用ODBC从Java读取Visual Foxpro数据

时间:2013-05-10 11:12:39

标签: java jdbc odbc visual-foxpro jdbc-odbc

我正在尝试从我的Java应用程序查询dbf表。我参考了这个thread

我使用ODBC数据源管理器创建了一个系统数据源,我将数据源名称设置为VFPDS,并将数据库类型设置为.DBC,最后设置.dbc文件的路径。

以下是我的java代码:

import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
// Import custom library containing myRadioListener
import java.sql.DriverManager;

public class testodbc {

public static void main( String args[] )
{
    try
    {
        // Load the database driver
        Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;

        // Get a connection to the database
        Connection conn = DriverManager.getConnection( "jdbc:odbc:VFPDS" ) ;

        // Print all warnings
        for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
        {
            System.out.println( "SQL Warning:" ) ;
            System.out.println( "State  : " + warn.getSQLState()  ) ;
            System.out.println( "Message: " + warn.getMessage()   ) ;
            System.out.println( "Error  : " + warn.getErrorCode() ) ;
        }

        // Get a statement from the connection
        Statement stmt = conn.createStatement() ;

        // Execute the query
        ResultSet rs = stmt.executeQuery( "SELECT * FROM pmsquoteh" ) ;//code crashes here

        // Loop through the result set
        while( rs.next() )
            System.out.println( rs.getString(1) ) ;

        // Close the result set, statement and the connection
        rs.close() ;
        stmt.close() ;
        conn.close() ;
    }
    catch( SQLException se )
    {   se.printStackTrace();
        System.out.println( "SQL Exception:" ) ;

        // Loop through the SQL Exceptions
        while( se != null )
        {   se.printStackTrace();
            System.out.println( "State  : " + se.getSQLState()  ) ;
            System.out.println( "Message: " + se.getMessage()   ) ;
            System.out.println( "Error  : " + se.getErrorCode() ) ;

            se = se.getNextException() ;
        }
    }
    catch( Exception e )
    {
        System.out.println( e ) ;
    }
}
}

我遇到了这个例外:

java.sql.SQLException: [Microsoft][ODBC Visual FoxPro Driver]Not a table.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at UsingButtons.main(testodbc.java:38)

SQL Exception:
State  : S0002
Message: [Microsoft][ODBC Visual FoxPro Driver]Not a table.
Error  : 123

我确信表pmsquoteh退出数据库,我的机器是64位机器。 我究竟做错了什么 ?我将很感激具体的答案。

3 个答案:

答案 0 :(得分:0)

我能够在Windows 7上使用jdbc-odbc桥访问FoxPro表,但它花了很多步。我已经安装了VFP驱动程序,我不记得我从哪里下载它,所以我没有链接。

我在这里复制了jbdc:odbc示例中的代码:http://www.java2s.com/Code/Java/Database-SQL-JDBC/SimpleexampleofJDBCODBCfunctionality.htm

DriverManager.getConnection方法采用数据库URL。要创建URL,您需要使用ODBC管理器。不幸的是,我可以通过控制面板访问的ODBC管理器仅适用于64位数据源。我不知道64位foxpro驱动程序。

要生成32位DSN,您需要运行32位ODBC管理器:odbcad32.exe。我的机器有几个副本。我从C:\ Windows \ SysWOW64运行了一个。转到系统DSN选项卡,然后选择Microsoft Visual Foxpro驱动程序。单击完成后,您将看到一个对话框,询问FoxPro数据库或表的数据源名称,描述和路径。您还必须指定是否要连接到.dbc或空闲​​表目录。您的错误消息让我想知道您的DSN上是否选择了错误的选项。

我传入getConnection方法的数据库URL是“jdbc:odbc:mydsnname”。

我跑了之后,收到了一个错误:

  

[Microsoft] [ODBC驱动程序管理器]指定的DSN包含   驱动程序和应用程序之间的体系结构不匹配

这是因为我使用的是64位JVM和32位DSN。我下载了一个32位的JVM,并能够用它来运行我的示例类。

我不知道是否有一个可以在64位JVM上设置的开关告诉它以32位运行。

答案 1 :(得分:0)

我从这里使用了JDBC驱动程序:

http://www.csv-jdbc.com/relational-junction/jdbc-database-drivers-products/new-relational-junction-dbf-jdbc-driver/

对我来说很好。在目前的测试中(大约一个小时),它会读取MEMO文件,并且似乎没有任何与DBC包含的表或免费DBF有关的问题。

不确定此驱动程序的成本。由于VFP已经过时,客户最多只需支付100美元。

答案 2 :(得分:0)

过去六个月我一直在使用javadbf-0.4.0.jar,并且没有问题。我将发布我的Java类和主程序。

package foxtablereader.src;

import java.sql.Connection;
import java.sql.SQLException;
import sun.jdbc.rowset.CachedRowSet;

/**
 *
 * @author kalimk
 */
public class DbfMain {

    static CachedRowSet crs;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SQLException {

       
        DbfConnection foxconn = new DbfConnection();
        Connection connection = null;
                
        String inputTablePath = "c:\\vfp_table\\";
        connection = foxconn.connection(inputTablePath);

        String query = "SELECT * FROM TrigExport2.dbf ";

        crs = foxconn.select(query, connection);
        //crs = ft.query(query, inputTablePath);
        System.out.println(" Size " + crs.size());
        while (crs.next()) {
            System.out.println("DESC " + crs.getString("Serialnum") + " " + crs.getString("cmailcode"));
        }

        inputTablePath = "C:\\sourcecode\\FoxTableReader\\";
        connection = foxconn.connection(inputTablePath);
        query = "SELECT * FROM TrigExports.dbf ";
        crs = foxconn.select(query, connection);

        System.out.println(" Size " + crs.size());

        int z = 1;
        while (crs.next()) {
            System.out.println(z++ + "  " + crs.getString("Serialnum") + " " + crs.getString("cmailcode"));
        }

        inputTablePath = "C:\\sourcecode\\FoxTableReader\\";
        connection = foxconn.connection(inputTablePath);
        String queryinsert = "insert into Mcdesc (Desc,Mailcode,Del_type,Column1) values ('Kalim','KHAN', 'ERUM','KHAN')";
        foxconn.insertUpdate(queryinsert, connection);

        inputTablePath = "C:\\sourcecode\\FoxTableReader\\";
        connection = foxconn.connection(inputTablePath);
        String queryupdate = "update  Mcdesc set  Column1= 'Sadiqquie'  where Desc = 'Kalim'";
        foxconn.insertUpdate(queryupdate, connection);
    }

}


package foxtablereader.src;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.jdbc.rowset.CachedRowSet;

/**
 *
 * @author kalimk
 */
public class DbfConnection {

    public Connection connection(String inputTablePath) throws SQLException {

        Connection con = null;
        //String jdbURL = "jdbc:DBF:/C:\\vfp_table\\";
        String jdbURL = "jdbc:DBF:/" + inputTablePath;
        Properties props = new Properties();
        props.setProperty("delayedClose", "0");

        try {

            Class.forName("com.caigen.sql.dbf.DBFDriver");

            try {

                con = DriverManager.getConnection(jdbURL, props);

            } catch (SQLException ex) {
                Logger.getLogger(DbfConnection.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DbfConnection.class.getName()).log(Level.SEVERE, null, ex);
        }

        return con;
    }

    public CachedRowSet select(String cQuery, Connection con) {
        CachedRowSet crs = null;
        try {

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(cQuery);
            crs = new CachedRowSet();
            crs.populate(rs);
            stmt.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return crs;
    }

    public boolean insertUpdate(String cQuery, Connection con) {
        boolean crs = false;
        try {

            PreparedStatement pStmnt = con.prepareStatement(cQuery);
            crs = pStmnt.execute();
            pStmnt.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return crs;
    }

    public int insertUpdateCount(String cQuery, Connection con) {

        int count = 0;
        try {

            Statement stmt = con.createStatement();
            count = stmt.executeUpdate(cQuery);
            System.out.println("Number of rows updated in database =  " + count);
            stmt.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return count;
    }

    public int insertUpdateCount2(String cQuery, Connection con) {

        int count = 0;
        boolean crs = false;
        try {

            PreparedStatement pStmnt = con.prepareStatement(cQuery);
            count = pStmnt.executeUpdate(cQuery);
            pStmnt.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return count;
    }

    public static void DBDisconnect(Connection DBCon) {
        try {

            if (DBCon != null) {
                DBCon.close();
            }
        } catch (SQLException e) {
            System.out.println(e.toString());
        } finally {
            try {

                DBCon.close();
                //System.err.println("Fimally is always executed");
            } catch (SQLException ex) {
                Logger.getLogger(DbfConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}