jdbc操作mysql延时操作_使用JDBC操作MySql

本文详细介绍了如何使用Java JDBC进行数据库驱动注册、建立连接、执行SQL查询与更新操作,以及调用存储过程。首先,通过Class.forName()方法注册MySQL驱动,然后使用DriverManager.getConnection()获取连接。接着,创建Statement或PreparedStatement执行SQL,利用executeQuery()、executeUpdate()或execute()方法处理不同类型的SQL。最后,展示了如何调用存储过程并获取输出参数的值。注意,为提高效率,应尽量重用CallableStatement实例。

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 connectionStatement 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值