现在的位置: 首页 > 综合 > 正文

使用JDBC操作MySql

2013年12月05日 ⁄ 综合 ⁄ 共 4053字 ⁄ 字号 评论关闭
1、将你使用的驱动程序在驱动程序管理器中进行注册,示例代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not import com.mysql.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
}

2、驱动程序注册之后,就可以取得一个与相关数据库的连接,示例代码如下:

    ... try {
            Connection conn = DriverManager.getConnection

("jdbc:mysql://localhost/test?user=monty&password=greatsqldb");

            // Do something with the Connection

           ....
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

3、你可以使用DriverManager.getConnection() 或 DataSource.getConnection()来建立一个连

接,然后通过该连接的createStatement()方法创建一个语句的实例。一旦建立了一个语句的实

例,可以调用它的executeQuery(String) 方法来执行查询操作,查询的结果存储在结果集类中

。你还可以通过executeUpdate(String SQL)方法来更新数据库,返回值是数值型,表示受到影

响的记录的数目。如果你事前不知道执行的SQL语句是查询还是更新,那么execute(String SQL)

方法可以执行该语句,返回值是布尔型,true表示执行的是查询操作,false表示执行的是更新

操作。如果该操作是个查询,那么可以通过getResultSet()方法得到结果集;如果该操作是更新

,那么可以通过getUpdateCount()获得受影响的记录的数目。示例代码如下:
// assume conn is an already created JDBC connection
Statement stmt = null;
ResultSet rs = null;

try {
    stmt = conn.createStatement();
    rs = stmt.executeQuery("SELECT foo FROM bar");

    // or alternatively, if you don't know ahead of time that
    // the query will be a SELECT...

    if (stmt.execute("SELECT foo FROM bar")) {
        rs = stmt.getResultSet();
    }

    // Now do something with the ResultSet ....
} finally {
    // it is a good idea to release
    // resources in a finally{} block
    // in reverse-order of their creation
    // if they are no-longer needed

    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException sqlEx) { // ignore }

        rs = null;
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException sqlEx) { // ignore }

        stmt = null;
    }
}
4、调用存储在数据库中的过程,示例代码如下:
过程:
CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255), INOUT inOutParam INT)
BEGIN
    DECLARE z INT;
    SET z = inOutParam + 1;
    SET inOutParam = z;

    SELECT inputParam;

    SELECT CONCAT('zyxw', inputParam);
END

调用过程:
import java.sql.CallableStatement;

...

    //
    // Prepare a call to the stored procedure 'demoSp'
    // with two parameters
    //
    // Notice the use of JDBC-escape syntax ({call ...})
    //

    CallableStatement cStmt = conn.prepareCall("{call demoSp(?, ?)}");
    cStmt.setString(1, "abcdefg");

注意,prepareCall()方法是一个开销非常大的方法,因此你应该尽量少调用该方法,尽量重复

使用同一个CallableStatement实例。

如果你想获得过程的返回值,那么你应该将表示该返回值的变量进行注册,示例代码如下:
import java.sql.Types;

...
    //
    // Connector/J supports both named and indexed
    // output parameters. You can register output
    // parameters using either method, as well
    // as retrieve output parameters using either
    // method, regardless of what method was
    // used to register them.
    //
    // The following examples show how to use
    // the various methods of registering
    // output parameters (you should of course
    // use only one registration per parameter).
    //

    //
    // Registers the second parameter as output
    //

    cStmt.registerOutParameter(2);

    //
    // Registers the second parameter as output, and
    // uses the type 'INTEGER' for values returned from
    // getObject()
    //

    cStmt.registerOutParameter(2, Types.INTEGER);

    //
    // Registers the named parameter 'inOutParam'
    //

    cStmt.registerOutParameter("inOutParam");

    //
    // Registers the named parameter 'inOutParam', and
    // uses the type 'INTEGER' for values returned from
    // getObject()
    //

    cStmt.registerOutParameter("inOutParam", Types.INTEGER);

向过程传递参数的若干方法:
//
    // Set a parameter by index
    //

    cStmt.setString(1, "abcdefg");

    //
    // Alternatively, set a parameter using
    // the parameter name
    //

    cStmt.setString("inputParameter", "abcdefg");

    //
    // Set the 'in/out' parameter using an index
    //

    cStmt.setInt(2, 1);

    //
    // Alternatively, set the 'in/out' parameter
    // by name
    //

    cStmt.setInt("inOutParam", 1);

执行了过程之后,如何获得返回值:
 int outputValue = cStmt.getInt(1); // index-based

    outputValue = cStmt.getInt("inOutParam"); // name-based




抱歉!评论已关闭.