关于JDBC学习笔记(一)

加载JDBC驱动
try {
        // Load the JDBC driver 加载指定名称的类
   
   
        String driverName = "org.gjt.mm.mysql.Driver";
        Class.forName(driverName);
    } catch (ClassNotFoundException e) {
        // Could not find the driver
   
   
    }
列出加载的全部JDBC驱动名称
List drivers = Collections.list(DriverManager.getDrivers());
    for (int i=0; i<drivers.size(); i++) {
        Driver driver = (Driver)drivers.get(i);
    
        // Get name of driver 驱动名称
   
   
        String name = driver.getClass().getName();
        // Get version info 驱动程序的版本信息
   
   
        int majorVersion = driver.getMajorVersion();
        int minorVersion = driver.getMinorVersion();
        boolean isJdbcCompliant = driver.jdbcCompliant();
    }


连接Oracle 数据库
Connection connection = null;     try {         // Load the JDBC driver         String driverName = "oracle.jdbc.driver.OracleDriver";         Class.forName(driverName);             // Create a connection to the database         String serverName = "127.0.0.1";         String portNumber = "1521";         String sid = "mydatabase";         String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;         String username = "username";         String password = "password";         connection = DriverManager.getConnection(url, username, password);     } catch (ClassNotFoundException e) {         // Could not find the database driver     } catch (SQLException e) {         // Could not connect to the database     }
连接MYSQL 数据库
mysql> GRANT ALL PRIVILEGES ON *.* TO username@localhost     IDENTIFIED BY 'password' WITH GRANT OPTION;         Connection connection = null;     try {         // Load the JDBC driver         String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver         Class.forName(driverName);             // Create a connection to the database         String serverName = "localhost";         String mydatabase = "mydatabase";         String url = "jdbc:mysql://" + serverName +  "/" + mydatabase; // a JDBC url         String username = "username";         String password = "password";         connection = DriverManager.getConnection(url, username, password);     } catch (ClassNotFoundException e) {         // Could not find the database driver     } catch (SQLException e) {         // Could not connect to the database     }
连接SQL2000数据库
Connection connection = null;     try {         String driverName = "com.jnetdirect.jsql.JSQLDriver"; // NetDirect JDBC driver         String serverName = "127.0.0.1";         String portNumber = "1433";         String mydatabase = serverName + ":" + portNumber;         String url = "jdbc:JSQLConnect://" + mydatabase; // a JDBC url         String username = "username";         String password = "password";             // Load the JDBC driver         Class.forName(driverName);             // Create a connection to the database         connection = DriverManager.getConnection(url, username, password);     } catch (ClassNotFoundException e) {         // Could not find the database driver     } catch (SQLException e) {         // Could not connect to the database }
直接连接ODBC数据源,不用再注册ODBC数据源
private  void getConnect(){            try{              URL url=this.getClass().getResource("../DataBase/"+DBname.toString());              String uri = new String(url.toString());              String sql_url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+uri.substring(6);              connect = DriverManager.getConnection(sql_url);              statem = connect.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);              // 创建数据库操作类的实例,该管理器对该数据库享有修改的权限            }catch(SQLException er){//捕获错误 :: SQL错误               System.out.println("Driver can not get connection"+er.getMessage());               System.exit(0);//软件正常退出             }//end_catch();           }
列出全部创建的可以使用数据库连接接口

try {

        // Load the driver

        String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver

        Class.forName(driverName);

   

        // Get the Driver instance 获取驱动的实例类

        String url = "jdbc:mysql://a/b";

        Driver driver = DriverManager.getDriver(url);

   

        // Get available properties 获取可以使用的属性

        DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);

        for (int i=0; i<info.length; i++) {

            // Get name of property

            String name = info[i].name;

   

            // Is property value required?

            boolean isRequired = info[i].required;

   

            // Get current value

            String value = info[i].value;

   

            // Get description of property

            String desc = info[i].description;

   

            // Get possible choices for property; if null, value can be any string

            String[] choices = info[i].choices;

        }

    } catch (ClassNotFoundException e) {

       // Could not find the database driver

    } catch (SQLException e) {

    }

Here's the property values for the MySql driver:

    Name(isRequired): Description

        default: default value

        choices: ...

   

    HOST(true): Hostname of MySQL Server

        default: a

   

    PORT(false): Port number of MySQL Server

        default: 3306

   

    DBNAME(false): Database name

        default: b

   

    user(true): Username to authenticate as

        default: null

   

    password(true): Password to use for authentication

        default: null

   

    autoReconnect(false): Should the driver try to re-establish bad connections?

        default: false

        choices: true, false

   

    maxReconnects(false): Maximum number of reconnects to attempt if autoReconnect is true

        default: 3

   

    initialTimeout(false): Initial timeout (seconds) to wait between failed connections

        default: 2

查询数据库是否支持存储过程
try {         DatabaseMetaData dmd = connection.getMetaData();         if (dmd.supportsTransactions()) {             // Transactions are supported         } else {             // Transactions are not supported         }     } catch (SQLException e) {     }
假如发生操作时据库的错误,本次操作回滚,取消本次的全部操作

    try {

        // Disable auto commit 设置提交的为手动提交数据操作动作

        connection.setAutoCommit(false);

   

        // Do SQL updates...

   

        // Commit updates 提交数据库操作

        connection.commit();

        connection.setAutoCommit(true);

 

    } catch (SQLException e) {

        // Rollback update 取消本次全部的数据库操作

        connection.rollback();

    }

操作处理SQL Exception
try {         // Execute SQL statements... 操作SQL的语句     } catch (SQLException e) {         while (e != null) {             // Retrieve a human-readable message identifying the reason for the exception             String message = e.getMessage();                 // This vendor-independent string contains a code that identifies             // the reason for the exception.             // The code follows the Open Group SQL conventions.             String sqlState = e.getSQLState();                 // Retrieve a vendor-specific code identifying the reason for the exception.             int errorCode = e.getErrorCode();                 // If it is necessary to execute code based on this error code,             // you should ensure that the expected driver is being             // used before using the error code.                 // Get driver name             String driverName = connection.getMetaData().getDriverName();             if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) {                 // Process error...             }                 // The exception may have been chained; process the next chained exception             e = e.getNextException();         }     }
查询是否有SQL Warning 发生
try {         // Get warnings on Connection object         SQLWarning warning = connection.getWarnings();         while (warning != null) {             // Process connection warning             String message = warning.getMessage();             String sqlState = warning.getSQLState();             int errorCode = warning.getErrorCode();             warning = warning.getNextWarning();         }             // Create a statement         Statement stmt = connection.createStatement();             // Use the statement...             // Get warnings on Statement object         warning = stmt.getWarnings();         if (warning != null) {             // Process statement warnings...         }             // Get a result set         ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");         while (resultSet.next()) {             // Use result set                 // Get warnings on the current row of the ResultSet object             warning = resultSet.getWarnings();             if (warning != null) {                 // Process result set warnings...             }         }     } catch (SQLException e) {     }
获取数据库驱动的连接

try {

        DatabaseMetaData dmd = connection.getMetaData();

        String driverName = dmd.getDriverName();  // Mark Matthew's MySQL Driver

    } catch (SQLException e) {

    }

//The best you can do is to use the URL used to create the connection: 最好的方法

    try {

        // Create connection from URL

        Connection conn = DriverManager.getConnection(url, username, password);

   

        // Get driver from URL

        Driver driver = DriverManager.getDriver(url);

    } catch (SQLException e) {

    }

设置SQL操作返回的影响的行数
try {         // Get the fetch size of a statement         Statement stmt = connection.createStatement ();         int fetchSize = stmt.getFetchSize();             // Set the fetch size on the statement 设置返回的行数         stmt.setFetchSize(100);             // Create a result set 创建一个结果集         ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");             // Change the fetch size on the result set 指定结果集的容量         resultSet.setFetchSize(100);     } catch (SQLException e) {     }
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、概述: JDBC从物理结构上说就是Java语言访问数据库的一套接口集合。从本质上来说就是调用者(程序员)和实现者(数据库厂商)之间的协议。JDBC的实现由数据库厂商以驱动程序的形式提供。JDBC API 使得开发人员可以使用纯Java的方式来连接数据库,并进行操作。 ODBC:基于C语言的数据库访问接口。 JDBC也就是Java版的ODBC。 JDBC的特性:高度的一致性、简单性(常用的接口只有4、5个)。 1.在JDBC中包括了两个包:java.sql和javax.sql。 ① java.sql 基本功能。这个包中的类和接口主要针对基本的数据库编程服务,如生成连接、执行语句以及准备语句和运行批处理查询等。同时也有一些高级的处理,比如批处理更新、事务隔离和可滚动结果集等。 ② javax.sql 扩展功能。它主要为数据库方面的高级操作提供了接口和类。如为连接管理、分布式事务和旧有的连接提供了更好的抽象,它引入了容器管理的连接池、分布式事务和行集等。 注:除了标出的Class,其它均为接口。 API 说明 java.sql.Connection 与特定数据库的连接(会话)。能够通过getMetaData方法获得数据库提供的信息、所支持的SQL语法、存储过程和此连接的功能等信息。代表了数据库。 java.sql.Driver 每个驱动程序类必需实现的接口,同时,每个数据库驱动程序都应该提供一个实现Driver接口的类。 java.sql.DriverManager (Class) 管理一组JDBC驱动程序的基本服务。作为初始化的一部分,此接口会尝试加载在”jdbc.drivers”系统属性中引用的驱动程序。只是一个辅助类,是工具。 java.sql.Statement 用于执行静态SQL语句并返回其生成结果的对象。 java.sql.PreparedStatement 继承Statement接口,表示预编译的SQL语句的对象,SQL语句被预编译并且存储在PreparedStatement对象中。然后可以使用此对象高效地多次执行该语句。 java.sql.CallableStatement 用来访问数据库中的存储过程。它提供了一些方法来指定语句所使用的输入/输出参数。 java.sql.ResultSet 指的是查询返回的数据库结果集。 java.sql.ResultSetMetaData 可用于获取关于ResultSet对象中列的类型和属性信息的对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值