日期:2014-05-16  浏览次数:20505 次

JDBC插入数据库获取主键
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.hww.util.db.JDBCUtil;

/**
 * @className:JDBCTest.java
 * @classDescription:
 * @author:weiwei.huang
 * @createTime:2012-2-10
 */
public class GENERATEDTest {
	public static void main(String[] args) throws SQLException {
		test1();
		test2();
	}
	/**
	 * PreparedStatement测试
	 *
	 * @author weiwei.huang
	 * @createTime 2012-2-10
	 * @throws SQLException
	 */
	public static void test1() throws SQLException {
		//建立数据库连接
		Connection conn = JDBCUtil.getCon();
		//sql语句
		String sql = "INSERT INTO song(song,singer) VALUES(?,?)";
		// PreparedStatement.RETURN_GENERATED_KEYS,该常量指示生成的键应该可用于获取,继承于java.sql.Statement
		PreparedStatement prep = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
		prep.setString(1, "love");
		prep.setString(2, "萧亚轩");
		prep.executeUpdate();
		//获取由于执行此 Statement 对象而创建的所有自动生成的键。也是继承与java.sql.Statement
		ResultSet rs = prep.getGeneratedKeys();
		if (rs.next()) {
			System.out.println(rs.getInt(1));
		}
		//关闭连接
		JDBCUtil.closeCon(conn);
	}
	
	/**
	 * Statement测试
	 *
	 * @author weiwei.huang
	 * @createTime 2012-2-10
	 * @throws SQLException
	 */
	public static void test2() throws SQLException {
		Connection conn = JDBCUtil.getCon();
		String sql = "INSERT INTO song(song,singer) VALUES('love','萧亚轩')";
		Statement stmt = conn.createStatement();
		stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
		ResultSet rst = stmt.getGeneratedKeys();
		if (rst.next()) {
			System.out.println(rst.getInt(1));
		}
		JDBCUtil.closeCon(conn);
	}
}

?