jdbc 原始数据库连接

原始的数据库连接

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

import org.junit.Test;

public class TestJdbc {
    @Test
    public void test() {
        ResultSet rs = null;
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            // 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "123");
            // 创建预处理语句对象
            ps = conn.prepareStatement("select * from tb_user where id = ?");
            ps.setLong(1, 1L);
            // 执行查询语句
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getLong("id"));
                System.out.println(rs.getString("user_name"));
                System.out.println(rs.getString("name"));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

猜你喜欢

转载自blog.csdn.net/u010452388/article/details/80786594
今日推荐