在IDEA中对数据库进行操作

话不多说,直接上代码,备注解释的很详细

package MyTestJDBC;

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

public class Main {
    public static void main(String[] args)  {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //加载Class.forName();此时就可以将其加载到VM中调用com.mysql.jdbc.Driver这个类里的静态变量或方法
            Class.forName("com.mysql.jdbc.Driver");
        /*创建数据库链接  通过connection
         DriverManager.getConnection 方法来  获取数据库链接
        jdbc:mysql://  url协议  localhost指本机的IP地址   3306指端口号,定位某台主机中的一个应用程序
        test:将要进性操作的数据库名称
        问号之前表示访问的全路径      ?    问号之后表示请求数据
        password.表示数据库密码   多个键值对通过&连接   CharacterEncoding=UTF-8 编码格式为UTF-8
        */
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&useSSL=false&characterEncoding=UTF-8");

            System.out.println(connection);
            //创建操作命令 Statement
            //connection已经链接到了本地将要访问的数据库,通过connection.createStatement()来创建将要进行的操作语句
            statement = connection.createStatement();
            //执行操作命令
            //通过resultSet来接受执行statement.excuteQuery传递的sql语句
            //resultSet相当于list<map<String,字段类型>>这个结构,用来接受数据库执行sql语句后的返回结果
            resultSet = statement.executeQuery("select id,name,role,salary from emp");
            //处理结果集里的数据
            while (resultSet.next()){
                int id = resultSet.getInt("id");//接收字段为id的返回结果,下同
                String name = resultSet.getString("name");
                String role = resultSet.getString("role");
                BigDecimal salary = resultSet.getBigDecimal("salary");
                System.out.printf("id=%s,name=%s,role=%s,salary=%s%n",id,name,role,salary);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        }
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值