Saturday, June 02, 2007

用jdbc-odbc操作dbf文件

dbf分两种,一种是Dbase,另一种是Foxpro的

Dbase不用装驱动就可以操作

java 代码
  1. Connection connDbf = null;
  2. PreparedStatement psDbf = null;
  3. ResultSet rsDbf = null;
  4. //一个目录名称,下面存放DBF文件
  5. String filePath = "D:/temp";
  6. //一个DBF文件夹,实际文件名称为tbUser.dbf,这里做为表名不用扩展名就可以
  7. String fileName = "tbUser";
  8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  9. connDbf = DriverManager.getConnection("jdbc:odbc:DRIVER={Microsoft dBase Driver (*.dbf)};DBQ=" + filePath + ";","","");
  10. sql = "select * from " + fileName;
  11. psDbf = connDbf.prepareStatement(sql);
  12. rsDbf = psDbf.executeQuery();

另一种要装foxpro的驱动

java 代码
  1. Connection connDbf = null;
  2. PreparedStatement psDbf = null;
  3. ResultSet rsDbf = null;
  4. //一个目录名称,下面存放DBF文件
  5. String filePath = "D:/temp";
  6. //一个DBF文件夹,实际文件名称为tbUser.dbf,这里做为表名不用扩展名就可以
  7. String fileName = "tbUser";
  8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  9. String strurl = "jdbc:odbc:Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=" + filePath + ";Exclusive=No;";
  10. connDbf = DriverManager.getConnection(strurl);
  11. sql = "select * from " + fileName;
  12. psDbf = connDbf.prepareStatement(sql);
  13. rsDbf = psDbf.executeQuery();

Friday, June 01, 2007

读取foxpro格式的dbf文件

原文出处

终于整理完dbf文件读写的java源码,欢迎使用

修改以下代码

private void init(InputStream inputstream)
throws JDBFException
{
try
{
stream = new DataInputStream(inputstream);
int i = readHeader();
fields = new JDBField[i];
int j = 1;
for(int k = 0; k < i; k++)
{
fields[k] = readFieldHeader();
j += fields[k].getLength();
}


if(stream.read() < 1)
throw new JDBFException("Unexpected end of file reached.");
nextRecord = new byte[j];
try
{
//stream.readFully(nextRecord);
stream.read(new byte[263]);
stream.readFully(nextRecord);
}
catch(EOFException eofexception)
{
nextRecord = null;
stream.close();
}
}
catch(IOException ioexception)
{
throw new JDBFException(ioexception);
}
}

private int readHeader()
throws IOException, JDBFException

{
byte abyte0[] = new byte[16];
try
{
stream.readFully(abyte0);
}
catch(EOFException eofexception)
{
throw new JDBFException("Unexpected end of file reached.");
}
int i = abyte0[8];
if(i < 0)
i += 256;
i += 256 * abyte0[9];
i -= 264;
i = --i / 32;
//i = --i / 32;
//i--;
try
{
stream.readFully(abyte0);
}
catch(EOFException eofexception1)
{
throw new JDBFException("Unexpected end of file reached.");
}
return i;
}

dbf文件定义格式:http://www.clicketyclick.dk/databases/xbase/format/dbf.html