使用idea查詢數據庫內容


根據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);
        }

    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM