1 Class.forName()加载驱动
2 DriverManager获取Connect连接
3 创建Statement执行SQL语句
4 返回ResultSet查询结果
5释放资源
package cn.tree.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MenuDao { // 查询主目录 public void getMainList() { Connection connection = null; Statement st = null; ResultSet rs = null; try { // 1、加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 2、获取数据库连接 connection = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/tree", "root", "123321"); // 3、获取Statement对象,执行sql语句 String sql = "select * from main"; st = connection.createStatement(); rs = st.executeQuery(sql); // 4、处理sql执行结果 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id: " + id + " " + "name: " + name); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { // 5、释放资源 rs.close(); st.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) { MenuDao menuDao = new MenuDao(); menuDao.getMainList(); } }