根据id查询数据库中的一个内容:

1.连接数据库

2.编写带?的sql语句

3.预编译

4.填充占位符

5.执行操作

6.if判断是否有值,打印输出

7.关闭驱动

示例:

package cn.kgc.crud;

import cn.kgc.entity.User;
import cn.kgc.util.JDBCUtil;

import java.sql.*;

/**
 * Created by helloworld on 2020/6/24.
 * 根据id查询一个数据
 */
public class SelectUserById {

    public static void main(String[] args){
        Connection connection=null;
        PreparedStatement pstm=null;
        ResultSet rs=null;

        try {
            //1连接数据库
            Class.forName("com.mysql.jdbc.Driver");

            // 使用的技术:数据库名://ip:mysql端口/数据库名字

            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx", "rxxx", "xxxxx")

        //2.编写?sql

        String sql ="select * from user where id=?";

        //3.预编译

            pstm = connection.prepareStatement(sql);

            //4.填充占位符
            pstm.setObject(1,"1");

        //5.执行
             rs = pstm.executeQuery();

            //6判断是否有值,然后打印
            if(rs.next()){
                /*int id = rs.getInt(1);
                String name = rs.getString(2);
                int age = rs.getInt(3);
*/
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");

                User user  = new User(id,name,age);
                System.out.println(user.toString());

              //  System.out.println("id:"+id+",name:"+name+",age"+age);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //7.关闭

            JDBCUtil.closeResource2(rs,pstm,connection);
        }

    }


}