jdbc 啟動Mysql8.0失敗 :版本不同需要更改配置:heima資料
阿新 • • 發佈:2018-12-10
package itheima;
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try { // 載入資料庫驅動 Class.forName("com.mysql.cj.jdbc.Driver"); // 通過驅動管理類獲取資料庫連結 connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true", "root", "root"); // 定義sql語句 ?表示佔位符 String sql = "select * from user where username = ?"; // 獲取預處理statement preparedStatement = connection.prepareStatement(sql); // 設定引數,第一個引數為sql語句中引數的序號(從1開始),第二個引數為設定的引數值 preparedStatement.setString(1, "王五"); // 向資料庫發出sql執行查詢,查詢出結果集 resultSet = preparedStatement.executeQuery(); // 遍歷查詢結果集 while (resultSet.next()) { System.out.println(resultSet.getString("id") + " " + resultSet.getString("username")); } } catch (Exception e) { e.printStackTrace(); } finally { // 釋放資源 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
}