【转】Java连接Mysql,SQL Server, Access,Oracle

   mysql-connector-java-3.1.12-bin.jar置于JDK的/jre/lib/ext目录下 
  try 
  { 
  // 连接字符串 
    String connName = "jdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=gb2312"; 
  // 登录用户名 
    String dbUser = "root"; 
  // 登录密码 
    String dbPwd = "zhihua1124"; 

      Class.forName("com.mysql.jdbc.Driver"); 
  // 生成一个连接 
    Connection con = DriverManager.getConnection(connName, dbUser, dbPwd); 

    return con; 

  }catch(Exception e) 
  { 
   System.err.println("Connection the database is wrong  !!"); 
   return null; 
  } 
2 Java连接SQL Server 2005
   下载sqljdbc.jar置于JDK的/jre/lib/ext目录下 
   try 
  { 
  // 连接字符串 
    String connName = "jdbc:sqlserver://localhost:1433;integratedSecurity=true;databaseName=sqlserverdb"; 
  // 登录用户名 
   
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //2005 
      // Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//2000 
  // 生成一个连接 
    Connection con = DriverManager.getConnection(connName); 
       return con;   
  }catch(Exception e) 
  { 
      e.printStackTrace(); 
      return null;   
  } 
3 Java连接Access
  建立ODBC数据源,此处为accessdb 
   try 
  { 
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
   Connection con=DriverManager.getConnection("jdbc:odbc:accessdb"); 
   Statement stmt = con.createStatement(); 
   ResultSet rs   = stmt.executeQuery(sql); 
   while(rs.next()) 
   { 
    int id         = Integer.parseInt(rs.getString("id")); 
    String name    = rs.getString("name"); 
    String address = rs.getString("address"); 
           String phone   = rs.getString("phone"); 
    String email   = rs.getString("email"); 
    StudentInfo stu = new StudentInfo(id,name,address,phone,email); 
    allStudent.add(stu);     
   } 
   rs.close(); 
   stmt.close(); 
   return allStudent; 
  } 
  catch (Exception e) 
  { 
   e.printStackTrace(); 
   return null; 
  } 
4 Java连接Oracle
在Oracle的安装目录之中/Db_1/jdbc/lib找到classes12.jar,置于JDK的/jre/lib/ext目录下 
   同时在/Db_1/jdbc/lib解压classes12.zip,比方解压至D:/classes12,在环境变量classpath中添加 
   try 
  { 
       String name="oracle.jdbc.driver.OracleDriver"; 
    String url="jdbc:oracle:thin:@localhost:1521:oracledb"; 
    Class.forName(name).newInstance(); 
    Connection con=DriverManager.getConnection(url,"ddbi","ddbi"); 
       return con;   
  }catch(Exception e) 
  { 
      e.printStackTrace(); 
      return null;   
  }

原文地址:http://blog.csdn.net/zhihua1124/article/details/3309937

posted @ 2013-07-18 09:33  kangxi  阅读(302)  评论(0编辑  收藏  举报