JDBC(Driver & DriverManager)

导入架包

单元测试:

jdbc连接

package com.cskaoyan.jdbc;

import org.junit.Test;

import java.math.BigDecimal;
import java.sql.*;
import java.util.Properties;

/*
 * 单元测试:
 * a. 访问权限必须是public
 * b. 要求方法是成员方法
 * c. 方法的返回值类型必须是void
 * d. 没有参数
 */
public class FooDemo {
    @Test
    public void foo() throws SQLException {
        // 注册驱动
        Driver driver = new com.mysql.jdbc.Driver();
        // 获取连接
        String url = "jdbc:mysql://localhost:3306/jdbc_db";
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "r00tme");
        Connection conn = driver.connect(url, info);
        // 获取SQL执行平台
        Statement stmt = conn.createStatement();
        // 执行SQL
        String sql = "select * from t_user";
        ResultSet rs = stmt.executeQuery(sql);
        // 处理结果
        while (rs.next()) {
            // MySQL索引是从1开始的
            int id = rs.getInt(1);
            String name = rs.getString(2);
            String password = rs.getString(3);
            BigDecimal balance = rs.getBigDecimal(4);
            System.out.println(id + " " + name + " " + password + " " + balance);
        }
        // 断开连接,释放资源
        rs.close();
        stmt.close();
        conn.close();
    }
}

版本1:

扫描二维码关注公众号,回复: 12408728 查看本文章

版本2:

版本3:(不是硬编码了)

通过把代码放入db

代码:

版本4:

版本5:(导入架包时,会自动加载)

代码:

猜你喜欢

转载自blog.csdn.net/weixin_41988545/article/details/106546694