1 JDBC查询的实现

1.数据库建表
1 JDBC查询的实现_第1张图片
2.代码实现

public class Demo1 {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;

        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //拿到con对象
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "fjtgyxa828998");
            //写sql语句
            String sql="select * from stu";
            //获取SQL对象
            statement = connection.createStatement();
            //执行SQL语句
            resultSet = statement.executeQuery(sql);
            resultSet.next();
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("编号   "+id);
            System.out.println("姓名   "+name);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }


    }
}

3.结果

编号   2
姓名   jun

Process finished with exit code 0

你可能感兴趣的:(JDBC)