加载驱动程序:
Class.forName(driverClass) //加载MySql驱动 Class.forName("com.mysql.jdbc.Driver") //加载Oracle驱动 Class.forName("oracle.jdbc.driver.OracleDriver")
获得数据库连接:
String url = "jdbc:mysql://localhost:3306/student"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password);
创建Statement对象:
Statement statement = connection.createStatement();
例子:
package com.silentteller.test; import java.sql.*; public class Test { public static void main(String[] args) { try { //1.加载驱动程序 Class.forName("com.mysql.cj.jdbc.Driver"); //2. 获得数据库连接 String url = "jdbc:mysql://localhost:3306/student"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); //3.操作数据库,实现增删改查 Statement statement = connection.createStatement(); String sql = "select * from student"; ResultSet rs = statement.executeQuery(sql); //如果有数据,rs.next()返回true while(rs.next()){ System.out.println(rs.getString("id") + rs.getString("student_id") + rs.getString("name") + rs.getInt("age") + rs.getString("sex") + rs.getString("birthday")); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } }