JDBC返回执行INSERT语句后的自增ID

package org.bw88;

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

import com.mysql.jdbc.Connection;

public class conmysql {

    public static void main(String[] args) throws Exception {
       String conString="jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8";
       String user="root";
       String  password="root";
       Connection conn=(Connection) DriverManager.getConnection(conString, user, password);
       /**
        * 插入数据,并获取自增ID,获取的是最后一次插入的记录的ID,前提是id是自增的,
       */
     /*  Statement  statement=conn.createStatement();*/
        String sql="INSERT INTO user_table(username,password)  VALUES(?,?)";
        PreparedStatement ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, "tpl");
        ps.setString(2, "888");
        ps.executeUpdate();
        ResultSet rs=ps.getGeneratedKeys();
        while(rs.next()) {
            int id=rs.getInt(1);//返回指定列的值
            System.out.println("自增id="+id);
        }
      // statement.execute(sql);
        
     
    /**
     * 更新数据
     */
      /* Statement  statement=conn.createStatement();
       String sql="UPDATE user_table SET password='111' WHERE username='16060426'";
       //statement.execute(sql);
       int i=statement.executeUpdate(sql);
       System.out.println(i);*/
       
       
       /**
        * 删除数据
        */
      /* Statement  statement=conn.createStatement();
       String sql="delete from user_table WHERE username='16060426'";
       statement.equals(sql);
       int i=statement.executeUpdate(sql);
       System.out.println(i);*/
       
       /**
        * 查找
        */
     /*  String pass="223";
       Statement  statement=conn.createStatement();
//       String sql="select * from user_table WHERE password='223'";
       String sql="select * from user_table WHERE password='"+pass+"'";
       ResultSet rs=statement.executeQuery(sql);
       while(rs.next()) {
           StringBuffer sb=new StringBuffer()
                   .append("用户名:")
                   .append(rs.getString("username"))
                   .append("密码")
                   .append(rs.getString(2));
           System.out.println(sb);
       }*/
       
       
       /**
        * prepareStatement 参数查询
        */
    /*   String pass="223";
     
     String sql="select * from user_table WHERE password=?";
     PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql);
     ps.setString(1, pass);
     ResultSet rs=ps.executeQuery();
     while(rs.next()) {
         System.out.println("用户名:"+rs.getString("username"));
     }*/
    rs.close();

       
      ps.close();
       conn.close();
    }

}
 

猜你喜欢

转载自blog.csdn.net/qq_38210187/article/details/83511987
今日推荐