不同数据库JDBC小示例

package com.jdbc.accp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_ODBC_Demo {

   /**
    * @param args
    */
   public static void main(String[] args) {
     /**
     * 1.加载驱动程序
     * 2.基于驱动程序管理器获得连接对象
     * 3.基于连接对象获得处理器对象
     * 4.准备和执行sql命令
     * 5.处理结果集
     * 6.关闭连接
     */
     //JDBC-ODBC桥加ODBC数据源
     try {
       //1-1.加载驱动程序:JDBC-ODBC桥驱动---sun.jdbc.odbc.JdbcOdbcDriver
       //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       //Oracle驱动:Oracle.jdbc.driver.OracleDriver
       //1-2.数据库厂商提供的本地纯Java驱动---com.microsoft.jdbc.sqlserver.SQLServerDriver
      Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver");
       //Class.forName("oracle.jdbc.driver.OracleDriver");
        
        
       //2.基于驱动程序管理器获得连接对象
       //Connection conn = DriverManager.getConnection("jdbc:odbc:accpStudent", "", "");
      Connection conn = DriverManager.getConnection( "jdbc:odbc:;Driver=Microsoft Access Driver (*.mdb);DBQ=D:\\studentdata.mdb");
       //Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databasename=teacher","sa","123456");
       //Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@IP:1521:dbName","scott","tiger");
        
       //3.基于连接对象获得处理器对象
      Statement stmt = conn.createStatement();
        
       //4.准备和执行sql命令
      String sql = "insert into teacher values('T001','火箭','A05')";
       int i = stmt.executeUpdate(sql);
        
      System.out.println(i==1? "一条记录已插入!": "插入失败!");
        
       //5.关闭连接
      stmt.close();
      conn.close();
    } catch (ClassNotFoundException e) {
        System.out.println( "加载驱动失败"+e.getMessage());
    } catch (SQLException e) {
        System.out.println( "记录插入失败"+e.getMessage());
    }
  }
    
    
}

你可能感兴趣的:(职场,休闲)