ajaxjquery1031
ajaxjquery1031
2011-05-08 16:32
浏览 216
已采纳

java程序连接access数据库,路径问题?

下面是连接Access的代码
import java.sql.*;
public class Test
{

public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}
catch(ClassNotFoundException e)
{

System.out.println(""+e);
}
try
{
con=DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=[b]D:\123\data.mdb[/b]","","");
stmt=con.createStatement();
rs=stmt.executeQuery("select * from info");
while(rs.next())
{
String title=rs.getString(2);

System.out.print(" title:"+title+"\t");
}
con.close();
}
catch(SQLException e) {System.out.println(e);}
}

}

我想把它改成相对路径,即DBQ中不用绝对路径。
让当前程序能找到data.mdb,那么这个语句该怎么写。
帮忙修改一下连data.mdb的语句,谢谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • iihero
    iihero 2011-05-08 17:22
    已采纳

    给楼主一个完整的例子吧:
    假设abc.mdb放到data子目录下边:

    [code="java"]package mytest.db.access;

    import java.sql.*;

    public class TestAccess
    {
    public static void main(String args[])
    {
    Connection con;
    Statement stmt;
    ResultSet rs;
    try
    {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    }
    catch (ClassNotFoundException e)
    {
    System.out.println("" + e);
    }
    try
    {
    String path = TestAccess.class.getClassLoader().getResource("data\abc.mdb").getPath()
    .substring(1);
    path = java.net.URLDecoder.decode(path);
    System.out.println(path);
    con = DriverManager.getConnection(
    "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + path, "", "");
    stmt = con.createStatement();
    rs = stmt.executeQuery("select 1");
    while (rs.next())
    {
    String title = rs.getString(1);
    System.out.print(" title:" + title + "\t");
    }
    con.close();
    }
    catch (SQLException e)
    {
    System.out.println(e);
    }
    }
    }
    [/code]

    点赞 评论
  • shibushi114
    shibushi114 2011-05-08 16:54

    [code="java"]String path = this.getClass().getClassLoader().getResource("123\data.mdb").getPath().substring(1);

    con=DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+path,"",""); [/code]

    点赞 评论

相关推荐