JDBC插入数据库获取主键

来源:互联网 发布:js获取li标签的属性值 编辑:程序博客网 时间:2024/05/17 16:11
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.StatementPreparedStatement prep = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);prep.setString(1, "love");prep.setString(2, "萧亚轩");prep.executeUpdate();//获取由于执行此 Statement 对象而创建的所有自动生成的键。也是继承与java.sql.StatementResultSet 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);}}
文章转自:http://ihuangweiwei.iteye.com/blog/1402268
0 0
原创粉丝点击