时间:2021-07-01 10:21:17 帮助过:3人阅读
package jdbc_preparement; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class text_preparestartment { public static void main(String[] args) { // TODO Auto-generated method stub Connection con=simplecon.getConnection(); //创建JDBC连接,用封装好的自定义类 String sql="insert into t_user values(null,?,?,null);";try { PreparedStatement ps=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); //多一个参数,表示需要返回主键 ps.setString(1, "mike"); ps.setString(2, "4399"); ps.execute(); ResultSet re=ps.getGeneratedKeys(); //返回主键 re.next(); int n=re.getInt(1); System.out.println("自然增长的序号为"+n); //输出主键 simplecon.close(re); simplecon.close(ps); simplecon.close(con); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class simplecon { static Connection con; static Connection getConnection() { try{ con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","数据库用户名","数据库密码"); }catch(SQLException e){ e.printStackTrace(); } return con; } static void close(AutoCloseable a) { try { a.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
JDBC获得数据库表中的auto_increment类主键
标签:mys exception print [] font into ace 创建 set