学习了:https://blog.51cto.com/u_15241951/2841221
package com.stono; import java.sql.*; public class CountTradeMark { public static void main(String[] args) { String driverName ="com.mysql.jdbc.Driver"; String URL = "jdbc:mysql://127.0.0.1:3306/mydb"; String sql = "SELECT * FROM mydb.mytable"; String username = "root"; String password = ""; Connection conn = null; try{ //加载驱动 Driver.class.forName(driverName); //建立连接 conn = DriverManager.getConnection(URL,username,password); //创建statement来执行sql语句 Statement ps = conn.createStatement(); //结果集处理 ResultSet rs = ps.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString("name")+","+rs.getString("sex")+","+rs.getInt("age")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e){ e.printStackTrace(); } //关闭连接 finally{ if(conn!=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } } }