欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdbc查询

程序员文章站 2024-03-01 16:57:52
...

1.引入数据库驱动

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.44</version>
</dependency>
package cn.mln521.jdbc;

import java.sql.*;

public class JdbcTest {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
                //1.注册驱动 tomcat8+ 不需要 会自动注册
                Class.forName("com.mysql.jdbc.Driver");
                //2.通过驱动管理类获取数据库链接
                connection = DriverManager.getConnection("jdbc:mysql:///eesy?characterEncoding=utf-8", "root", "root");
                //3.定义sql  ?表示占位符
                String sql = "select * from user where id = ?";
                //4.获取预处理对象PrepareStatement对象
                ps = connection.prepareStatement(sql);
                //5. 设置参数并执行sql
                ps.setString(1,"41");
                rs = ps.executeQuery();
                //5.处理结果集
                if(rs.next()){
                    System.out.println("姓名:" +rs.getString("username"));
                    System.out.println("生日:" +rs.getString("birthday"));
                }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

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

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

        }
    }
}