分享

java使用MySQL学习

 青青小舟 2010-10-28

原创  java使用MySQL学习 收藏

1、创建 Statement 对象 

建立了到特定数据库的连接之后,就可用该连接发送 SQL 语句。

Statement 对象用 Connection 的方法 createStatement 创建,如下列代码段中所示:

  String sql = String.format("INSERT INTO %s ( %s ) VALUES ( %s )", table_A, AttList.toString(), ValList.toString()) 
  Class.forName("com.ibm.db2.jdbc.app.DB2Driver   ").newInstance();     
  String   url="jdbc:db2://localhost:5000/DBserverName";     
   //DBserverName为你的数据库名     
  String   user="admin";     
  String   password=""; 
  Connection m_lblDBconn = DriverManager.getConnection(url, user, password);

  Statement SQLDBStm = m_lblDBconn.createStatement();

//驱动数据库厂商就是根据JDBC的接口规范编写的实现类 当你加载注册一个数据库的驱动后 进行数据库操作时,就会生成驱动里面的具体类的对象 然后通过一个接口引用指向这个对象m_lblDBconn  Statement SQLDBStm = m_lblDBconn.createStatement() 你可以通过rtti得到获得具体对象 

为了执行 Statement 对象,被发送到数据库的 SQL 语句将被作为参数提供给 Statement 的方法: 

  int  ID = -1;

  SQLDBStm.executeUpdate( sql, Statement.RETURN_GENERATED_KEYS);

我们通过以下方法获得新增数据的主键值

  ResultSet rs = SQLDBStm.getGeneratedKeys();

  rs.first();

  if (rs.next()){

 ID = rs.getInt(1); //Obtain the new ID;

  }  

return Integer.toString(ID);

这里我们使用了获得自动生成主键的方法executeUpdate( sql, Statement.RETURN_GENERATED_KEYS);并使用getGeneratedKeys()

返回Id值

2、使用 Statement 对象执行语句 

Statement 接口提供了三种执行 SQL 语句的方法:executeQuery、executeUpdate 和 execute。使用哪一个方法由 SQL 语句所产生的内容决定。 

方法 executeQuery 用于产生单个结果集的语句,例如 SELECT 语句。 

方 法 executeUpdate 用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。INSERT、UPDATE 或 DELETE 语句的效果是修改表中零行或多行中的一列或多列。executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。 

方法 execute 用于执行返回多个结果集、多个更新计数或二者组合的语句。因为多数程序员不会需要该高级功能,所以本概述后面将在单独一节中对其进行介绍。 

执行语句的所有方法都将关闭所调用的 Statement 对象的当前打开结果集(如果存在)。这意味着在重新执行 Statement 对象之前,需要完成对当前 ResultSet 对象的处理。 

应 注意,继承了 Statement 接口中所有方法的 PreparedStatement 接口都有自己的 executeQuery、executeUpdate 和 execute 方法。Statement 对象本身不包含 SQL 语句,因而必须给 Statement.execute 方法提供 SQL 语句作为参数。PreparedStatement 对象并 不将 SQL 语句作为参数提供给这些方法,因为它们已经包含预编译 SQL 语句。CallableStatement 对象继承这些方法的 PreparedStatement 形式。对于这些方法的 PreparedStatement 或 CallableStatement 版本,使用查询参数将抛出 SQLException。

3、语句完成 

当连接处于自动提交模式时,其中所执 行的语句在完成时将自动提交或还原。语句在已执行且所有结果返回时,即认为已完成。对于返回一个结果集的 executeQuery 方法,在检索完 ResultSet 对象的所有行时该语句完成。对于方法 executeUpdate,当它执行时语句即完成。但在少数调用方法 execute 的情况中,在检索所有结果集或它生成的更新计数之后语句才完成。

4、关闭 Statement 对象 

Statement 对象将由 Java 垃圾收集程序自动关闭。而作为一种好的编程风格,应在不需要 Statement 对象时显式地关闭它们。这将立即释放 DBMS 资源,有助于避免潜在的内存问题。

statement-相关概述

Statement 对象用于将 SQL 语句发送到数据库中。实际上有三种 Statement 对象,它们都作为在给定连接上执行 statementSQL 语句的包容器:Statement、PreparedStatement(它从 Statement 继承而来)和 CallableStatement(它从 PreparedStatement 继承而来)。它们都专用于发送特定类型的 SQL 语句: Statement 对象用于执行不带参数的简单 SQL 语句;PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句;CallableStatement 对象用于执行对数据库已存储过程的调用。


Statement 接口提供了执行语句和获取结果的基本方法。PreparedStatement 接口添加了处理 IN 参数的方法;而 CallableStatement 添加了处理 OUT 参数的方法。

有些 DBMS 将已存储过程中的每条语句视为独立的语句;而另外一些则将整个过程视为一个复合语句。在启用自动提交时,这种差别就变得非常重要,因为它影响什么时候调用 commit 方法。在前一种情况中,每条语句单独提交;在后一种情况中,所有语句同时提交。

JDBC 3种获得mysql插入数据的自增字段值的方法

1. Retrieving AUTO_INCREMENT Column Values using Statement.getGeneratedKeys()
2. Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()
3. Retrieving AUTO_INCREMENT Column Values in Updatable ResultSets

 

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

public class RetrievAutoIncrementTest {

 public void init() throws Exception {
  Statement stmt = null;
  ResultSet rs = null;
  Connection conn = null;
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager
     .getConnection("jdbc:mysql://localhost/test?","root", "admin");
   // Issue the DDL queries for the table for this example
   stmt = conn.createStatement();
   stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");

  //创建数据库表autoIncTutorial。
   stmt.executeUpdate("CREATE TABLE autoIncTutorial ("
     + "priKey INT NOT NULL AUTO_INCREMENT, "
     + "dataField VARCHAR(64), PRIMARY KEY (priKey))");
  } finally {
   if (rs != null) {
    try {
     rs.close();
    } catch (Exception e) {
    }
   }
   if (stmt != null) {
    try {
     stmt.close();
    } catch (Exception e) {
    }
   }
   if (conn != null) {
    try {
     conn.close();
    } catch (Exception e) {
    }
   }
  }
 }

方法1:

 public void test1() throws Exception {
  Statement stmt = null;
  ResultSet rs = null;
  Connection conn = null;
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager
     .getConnection("jdbc:mysql://localhost:3306/test","root", "admin");
   // Create a Statement instance that we can use for
   // 'normal' result sets assuming you have a
   // Connection 'conn' to a MySQL database already available
   stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
     java.sql.ResultSet.CONCUR_UPDATABLE);
   //Insert one row that will generate an AUTO INCREMENT key in the 'priKey' field
     for (int i = 0; i < 10; i++) {
    stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) "
      + "values ('Can I Get the Auto Increment Field?')",
      Statement.RETURN_GENERATED_KEYS);
     // Example of using Statement.getGeneratedKeys()
    // to retrieve the value of an auto-increment value
    int autoIncKeyFromApi = -1;
    rs = stmt.getGeneratedKeys();
    if (rs.next()) {
     
autoIncKeyFromApi = rs.getInt(1);
    } else {
     // throw an exception from here
    }
    rs.close();
    rs = null;
    System.out.println("Key returned from getGeneratedKeys():"
      + autoIncKeyFromApi);
   }
  } finally {
   if (rs != null) {
    try {
     rs.close();
    } catch (Exception e) {
    }
   }
   if (stmt != null) {
    try {
     stmt.close();
    } catch (Exception e) {
    }
   }
   if (conn != null) {
    try {
     conn.close();
    } catch (Exception e) {
    }
   }
  }
 }

方法2:

 public void test2() throws Exception {
  Statement stmt = null;
  ResultSet rs = null;
  Connection conn = null;
  try {

   //
   // Create a Statement instance that we can use for
   // 'normal' result sets.
   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager
     .getConnection("jdbc:mysql://localhost/test","root", "admin");

   stmt = conn.createStatement();
   // Insert one row that will generate an AUTO INCREMENT
   // key in the 'priKey' field
   for (int i = 0; i < 10; i++) {
    stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) "
      + "values ('Can I Get the Auto Increment Field?')");
    // Use the MySQL LAST_INSERT_ID() function to do the same thing as getGeneratedKeys()
    int autoIncKeyFromFunc = -1;
    rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");

    if (rs.next()) {
     autoIncKeyFromFunc = rs.getInt(1);
    } else {
     // throw an exception from here
    }
    rs.close();
    System.out.println("Key returned from "
      + "'SELECT LAST_INSERT_ID()': " + autoIncKeyFromFunc);
   }
  } finally {
   if (rs != null) {
    try {
     rs.close();
    } catch (Exception e) {
    }
   }
   if (stmt != null) {
    try {
     stmt.close();
    } catch (Exception e) {
    }
   }
   if (conn != null) {
    try {
     conn.close();
    } catch (Exception e) {
    }
   }
  }
 }

方法3:

 public void test3() throws Exception {
  Statement stmt = null;
  ResultSet rs = null;
  Connection conn = null;
  try {
   // Create a Statement instance that we can use for
   // 'normal' result sets as well as an 'updatable'
   // one, assuming you have a Connection 'conn' to a MySQL database already available

   Class.forName("com.mysql.jdbc.Driver");
   conn = DriverManager
     .getConnection("jdbc:mysql://localhost/test","root", "admin");
   stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
     java.sql.ResultSet.CONCUR_UPDATABLE);
   for (int i = 0; i < 10; i++) {
    // Example of retrieving an AUTO INCREMENT key from an updatable result set
    rs = stmt.executeQuery("SELECT priKey, dataField "+ "FROM autoIncTutorial");

    rs.moveToInsertRow();
    rs.updateString("dataField", "AUTO INCREMENT here?");
    rs.insertRow();
    // the driver adds rows at the end
    rs.last();
    // We should now be on the row we just inserted
    int autoIncKeyFromRS = rs.getInt("priKey");
    rs.close();
    rs = null;
    System.out.println("Key returned for inserted row: "+ autoIncKeyFromRS);
   }
  } finally {
   if (rs != null) {
    try {
     rs.close();
    } catch (Exception e) {
    }
   }
   if (stmt != null) {
    try {
     stmt.close();
    } catch (Exception e) {
    }
   }
   if (conn != null) {
    try {
     conn.close();
    } catch (Exception e) {
    }
   }
  }
 }


 public static void main(String[] args) throws Exception {
  RetrievAutoIncrementTest test = new RetrievAutoIncrementTest();
  test.init();
  test.test1();  //测试第一种获取自增字段的值
  test.test2();  //测试第二种获取自增字段的值
  test.test3();  //测试第三种获取自增字段的值
 }

}

参考文献:

[1]  三种获得自动生成主键的方法,getGeneratedKeys,专用SQL和可更新的结果集

             http://blog.csdn.net/java2000_net/archive/2008/09/27/2989625.aspx

[2]    java Statement详细用法

             http://hi.baidu.com/shifeng121/blog/item/0a38c3588e5fa589810a18c7.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多