版本:
mysql-connector-java-6.0.2-bin.jar
mysql : 5.7.11
import com.mysql.cj.api.jdbc.Statement; public class test { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); Connection conn = null; String urlString = "jdbc:mysql://localhost:3306/javademo?user=root&password=123" + "&characterEncoding=utf8" + "&useSSL=true&serverTimezone=UTC"; conn = DriverManager.getConnection(urlString); Statement sat = (Statement) conn.createStatement(); String sql = "select * from student"; ResultSet result = sat.executeQuery(sql); int numCol = result.getMetaData().getColumnCount(); while (result.next()) { for (int i = 1; i <= numCol; i++) { System.out.println(result.getString(i)); } } } catch (Exception ex) { ex.printStackTrace(); } } }
更新:
1.Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
2."&useSSL=true&serverTimezone=UTC" 必须滴
3.在JDK1.5之后,其实已经不需要去显式调用Class.forName("com.mysql.cj.jdbc.Driver")了,DriverManager会自动去加载合适的驱动,但是前提是CLASSPATH下必须有驱动jar包。