mysql挿入データを実行したidを取得

1683 ワード

package com.test.javaSe01;

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

public class JDBCTestDemo01 {
	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/test?unicode=true&characterEncoding=utf8";
		String driver = "com.mysql.jdbc.Driver";
		String user = "root";
		String password = "root";
		Connection conn = null;
		Statement st = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(url, user, password);
			// rs = conn.createStatement().executeQuery("select * from test01");
			// while (rs.next()) {
			// System.out.println(rs.getInt(1) + " " + rs.getString(2));
			// }
			st = conn.createStatement();
			ps = conn.prepareStatement("insert into test01 (name) values(?)",Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, javax.swing.JOptionPane.showInputDialog("  name"));
			// st.executeUpdate(");
			// rs=st.getGeneratedKeys();
			ps.executeUpdate();
			rs=ps.getGeneratedKeys();
			rs.next();
			int id = rs.getInt(1);
			rs.next();
			System.out.println(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			System.err.println("      !");
			e.printStackTrace();
		}
	}
}