最近需要用java做一个小功能,需要链接access 数据库 ,在网上找了好多, 方法 都差不多,现总结下,供大家参考。 我的office版本是2010的,所以access 数据库 文件的后缀是.accdb,在发布系统的时候, 数据库 文件放在项目中跟tomcat一起发布,这样方便部署
最近需要用java做一个小功能,需要链接access数据库,在网上找了好多,方法都差不多,现总结下,供大家参考。
我的office版本是2010的,所以access数据库文件的后缀是.accdb,在发布系统的时候,数据库文件放在项目中跟tomcat一起发布,这样方便部署。
1、获取数据库路径:
// 获取数据库文件路径
public static string getpath(){
string path = ;
string projectname=test;
path = system.getproperty(user.dir); // 获取到tomcat的bin目录地址
path = path.replace(bin, webapps)+\\+projectname+\\data\\test.accdb;
return path;
}
2、建立数据库连接:
url中,*.mdb, *.accdb 这两个之间要有空格,否则会报错误:java.sql.sqlexception: [microsoft][odbc 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序;
pwd是数据库密码,如果没有的话可以不用写。
// 建立数据库链接
public static connection getconnection() throws sqlexception, classnotfoundexception{
string path = getpath();
string url = jdbc:odbc:driver={microsoft access driver (*.mdb, *.accdb)};dbq=+path+ ;pwd=123456789;
class.forname(sun.jdbc.odbc.jdbcodbcdriver);
connection conn = drivermanager.getconnection(url);
return conn;
}
3、简单查询数据:
// 根据sql语句,返回查询结果的第一行第一列
public static string getscalar(string strsql) {
string rvalue = ;
connection conn = null;
try {
conn = getconnection();
statement st = conn.createstatement();
//system.out.println(strsql);
resultset rs = st.executequery(strsql);
if (rs.next()) {
rvalue = rs.getstring(1);
}
rs.close();
st.close();
conn.close();
} catch (exception e) {
system.out.println(数据库连接发生错误,错误信息: + e.tostring());
} finally {
try {
if (conn != null && !conn.isclosed())
conn.close();
} catch (sqlexception ex1) {
system.out.println(数据库关闭发生错误,错误信息: + ex1.tostring());
}
}
return rvalue;
}
就先写到这里了,第一次写博客,有写的不好的地方或者代码不合适的地方欢迎大家指点。