在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(); } } }