Home >Database >Mysql Tutorial >JAVA访问Access数据库

JAVA访问Access数据库

WBOY
WBOYOriginal
2016-06-07 15:36:511148browse

/** * JAVA访问Access数据库 * 因为没有像访问其它数据库的驱动程序 * 所以只能够通过ODBC的形式访问 * 示例表:create table user(id int,name char(50),age int),id为自增型 */ import java.sql.*; public class Access_Conn { public Connection getConn

 /**
 * JAVA访问Access数据库
 * 因为没有像访问其它数据库的驱动程序
 * 所以只能够通过ODBC的形式访问
 * 示例表:create table user(id int,name char(50),age int),id为自增型
 */
import java.sql.*;
public class Access_Conn {

 public Connection getConn() {
  //test为配置的数据源名
  String url = "jdbc:odbc:test";
  Connection con = null;
  try {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   con = DriverManager.getConnection(url, "", "");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return con;
 }
 public static void main(String[] arg)
 {
  Access_Conn con=new Access_Conn();
  Connection conn=con.getConn();
  try {
   Statement st=conn.createStatement();
   st.execute("insert into user(name,age) values('test',20)");
   ResultSet rs=st.executeQuery("select * from user");
   while(rs.next())
   {
    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getInt(3));
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally{
   try {
    if(conn!=null)
     conn.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
 }
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn