当前位置: 技术问答>java相关
如何用jdbc连接Access数据库(用可读写的模式)
来源: 互联网 发布时间:2015-05-07
本文导语: rt | 这方面的资料网上很多! 给个简单的例子吧. testAccess是DNS名。 Connection connection=null; PreparedStatement statement=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection=DriverManager.getConnectio...
rt
|
这方面的资料网上很多!
给个简单的例子吧.
testAccess是DNS名。
Connection connection=null;
PreparedStatement statement=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection=DriverManager.getConnection("jdbc:odbc:testAccess","","");
}
catch(Exception e)
{
e.printStackTrace();
}
//取驱动程序
try{
String sql="select * from test";
statement=connection.prepareStatement(sql);
ResultSet result=statement.executeQuery();
while(result.next())
{
int nid=result.getInt("id");
String strid=new String("id "+nid);
System.out.println(strid);
String name=result.getString("username");
System.out.println("name "+name);
String sex=result.getString("old");
System.out.println("sex "+sex);
// int age=result.getInt("age");
// String strAge=new String(""+age);
// System.out.println("age "+strAge);
String phone=result.getString("birthday");
System.out.println("phone "+phone);
}
result.close();
statement.close();
}catch(Exception e)
{
System.out.println(e.toString());
}
给个简单的例子吧.
testAccess是DNS名。
Connection connection=null;
PreparedStatement statement=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection=DriverManager.getConnection("jdbc:odbc:testAccess","","");
}
catch(Exception e)
{
e.printStackTrace();
}
//取驱动程序
try{
String sql="select * from test";
statement=connection.prepareStatement(sql);
ResultSet result=statement.executeQuery();
while(result.next())
{
int nid=result.getInt("id");
String strid=new String("id "+nid);
System.out.println(strid);
String name=result.getString("username");
System.out.println("name "+name);
String sex=result.getString("old");
System.out.println("sex "+sex);
// int age=result.getInt("age");
// String strAge=new String(""+age);
// System.out.println("age "+strAge);
String phone=result.getString("birthday");
System.out.println("phone "+phone);
}
result.close();
statement.close();
}catch(Exception e)
{
System.out.println(e.toString());
}
|
gja106的代码可以加上两行,更加经典
try{
...
}catch(Exception e){
...
}finally{
result.close();
statement.close();
}
try{
...
}catch(Exception e){
...
}finally{
result.close();
statement.close();
}
|
ACCESS只能使用JDBC-ODBC连接
可以看看这方面的列子,很多,也挺简单
可以看看这方面的列子,很多,也挺简单
|
取得connection的地方
String url = "jdbc:odbc:yourdsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(url,"tester","password");
String url = "jdbc:odbc:yourdsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(url,"tester","password");