java-7: 使用JDBC驅動連接mysql數據庫遇到的若干問題

如下在eclipse(Java EE IDE)使用JDBC連接MySql數據庫,進行一個簡單的select程序,只要能查詢數據庫,其他的都好辦。

本文涉及兩類問題:第一類是驅動報錯,第二類是數據庫連接報錯。

以下代碼是完整的驅動和數據庫連接配置。

package org.szxu.volatileTest;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;

public class DBTest {
	public static void JDBCRead(){		
		//裝載驅動
		try {
			//String driverName = "com.mysql.jdbc.Driver";  //舊版本,這裏用的是:mysql-connector-java-5.1.46-bin.jar
			String driverName = "com.mysql.cj.jdbc.Driver";  //新版本,這裏用的是:mysql-connector-java-8.0.11.jar
			Class.forName(driverName);		
			System.out.println("MYSQL JDBC Driver is loaded successfully!");
		}catch(ClassNotFoundException e){
			System.out.println("Where is your MYSQL JDBC Driver?");
			e.printStackTrace();
			return;
		}
		
		//連接數據庫
		//String url = "jdbc:mysql://127.0.0.1:3306/crm";  //報錯:
		String url = "jdbc:mysql://127.0.0.1:3306/crm?useSSL=false&serverTimezone=GMT";  //數據庫連接串,正確
		String user = "root";  //用戶名
		String passWord = "admin";  //密碼
		Connection connection = null;
		Statement stmt = null;
		try {
			connection = DriverManager.getConnection(url, user, passWord);
			if(connection != null) {
				stmt = connection.createStatement();
				String sql = "select id, name, score from student";
				ResultSet rs = stmt.executeQuery(sql);
				while(rs.next()) {
					System.out.print("id:" + rs.getString("id") + " ");
					System.out.print("name:" + rs.getString("name") + " ");
					System.out.print("score:" + rs.getInt("score") + "\r\n");
				}
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		finally {
			try {
				connection.close();
				stmt.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}

第一類問題:驅動名稱報錯,驅動更換報錯:

(1)驅動名稱報錯:【Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

驅動名稱報錯分析:在使用舊版本mysql-connector-java-5.1.46-bin.jar時,使用的driverName = "com.mysql.jdbc.Driver",但是如果切換到mysql-connector-java-8.0.11.jar,就要使用driverName = "com.mysql.cj.jdbc.Driver"。否則報如上錯誤。

(2)驅動更換報錯:【錯誤: 找不到或無法加載主類 org.szxu.volatileTest.Program

這個錯誤非常隱蔽,必須查看“problems”的Tab頁,原因是在更換驅動時,是直接到lib文件夾中,右擊文件刪除的,此時編譯目錄中還有殘留路徑,因此會報如上圖無法編譯(必須重新clean一次再run,否則還是上一次的編譯結果)。如下圖只需要在項目上右擊選中build path -- configure buid path -- libraries,刪除無用的驅動文件即可。

第二類問題:數據庫連接報錯

(1)傳輸加密未設定方式報錯:【Thu Oct 03 10:30:13 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

只需要在URL中添加“useSSL=false”即可;

(2)數據庫返回時間問題報錯:【The server time zone value '???ú±ê×??±??' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

只需要在URL中添加“serverTimezone=GMT”即可。每項配置之間用“&”連接,第一項配置之前要放“?”

---------------------------------------------------------

附錄:驅動的下載和配置請參考下一篇博文

---------------------------------------------------------

參考文章:

1.https://blog.csdn.net/jabony/article/details/90242860,關於“傳輸加密未設定方式報錯"。

2.https://blog.csdn.net/weixin_37577564/article/details/80329775,關於“數據庫返回時間問題報錯”。

---------------------------------------------------------

--封裝後的源碼:

package org.szxu.volatileTest;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;

public class MySqlDBTest {
	private MySqlDBTest() { 
		//String driverName = "com.mysql.jdbc.Driver";  //舊版本,這裏用的是:mysql-connector-java-5.1.46-bin.jar
		String driverName = "com.mysql.cj.jdbc.Driver";  //新版本,這裏用的是:mysql-connector-java-8.0.11.jar
		mySqlDBInite(driverName);
	}
	
	public static MySqlDBTest dbTest = null;
	public static Connection connection = null;
	//public static String url = "jdbc:mysql://127.0.0.1:3306/crm";  //報錯:
	public static String url = "jdbc:mysql://127.0.0.1:3306/crm?useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true";  //數據庫連接串,正確
	public static String user = "root";  //用戶名
	public static String passWord = "admin";  //密碼
	private static String obj = "lock";
	
	public static MySqlDBTest instance() {
		if(dbTest == null){
			synchronized(obj) {
				if(dbTest == null) {
					dbTest = new MySqlDBTest();
				}
			}
		}
		return dbTest;
	}
	
	/**
	 * JDBC初始化驅動裝載
	 * @param driverName
	 */
	public static boolean mySqlDBInite(String driverName){
		//裝載驅動
		try {			
			Class.forName(driverName);		
			System.out.println("MYSQL JDBC Driver is loaded successfully!");
			return true;
		}catch(ClassNotFoundException e){
			System.out.println("Where is your MYSQL JDBC Driver?");
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 獲取數據庫連接
	 * @return
	 */
	public static synchronized Connection getConnection(){
		if(connection == null) {
			try {
				connection = DriverManager.getConnection(url, user, passWord);
			}catch(SQLException e) {
				e.printStackTrace();
			}
			
			if(connection == null) {
				System.out.println("Wrong, MYSQL database connects failed!");
			}
			else {
				System.out.println("MYSQL database connects successfully!");
			}
		}
		
		return connection;
	}
	
	/**
	 * 操作數據庫:statement方式
	 */
	public void StatementOperate(){
		Connection connection = getConnection();
		if(connection == null){
			return;
		}
		
		Statement stmt = null;    // 僅需要創建一次即可
		try {
			//statement對象
			stmt = connection.createStatement();
			
			//查
			printStudentData(connection);
			
			//改
			String sql = "update student set score = 85 where id = 3";
			int affectedRows = stmt.executeUpdate(sql);
			System.out.printf(String.format("student表,更新數量=%d\r\n", affectedRows));
			
			//增
			sql = "insert into student(name, score) select 'jlxu', '65'";
			affectedRows = stmt.executeUpdate(sql);
			System.out.printf("student表,插入數量=%d\r\n", affectedRows);
			printStudentData(connection);
			
			//刪
			sql = "delete from student where name = 'jlxu'";
			affectedRows = stmt.executeUpdate(sql);
			System.out.printf("student表,刪除數量=%d\r\n", affectedRows);
			printStudentData(connection);
		}catch(SQLException e) {
			e.printStackTrace();
		}
		finally {
			try {
				connection.close();
				stmt.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 操作數據庫:prepared方式
	 */
	public void preparedOperate() {
		Connection connection = getConnection();
		if(connection == null){
			return;
		}
		
		PreparedStatement ps = null;    // 每次操作均需重新創建
		try {
			//查
			printStudentData(connection);
			
			//改
			String sql = "update student set score = 85 where id = 3";
			ps = connection.prepareStatement(sql);
			int affectedRows = ps.executeUpdate();
			
			//增
			sql = "insert into student(name, score) select 'jlxu', '65'";
			 
			ps = connection.prepareStatement(sql);
			affectedRows = ps.executeUpdate();
			System.out.printf("student表,插入數量=%d\r\n", affectedRows);
			printStudentData(connection);
			
			//刪
			sql = "delete from student where name = 'jlxu'";
			ps = connection.prepareStatement(sql);
			affectedRows = ps.executeUpdate();
			System.out.printf("student表,刪除數量=%d\r\n", affectedRows);
			printStudentData(connection);
			
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				connection.close();
				ps.close();
			}catch(SQLException ex) {
				ex.printStackTrace();
			}
		}
	}
	
	/**
	 * 查詢學生表數據
	 * @param connection
	 */
	public void printStudentData(Connection connection) {
		Statement stmt = null;
		ResultSet rs = null;
		try {
			//statement對象
			stmt = connection.createStatement();
			
			//查(使用ResultSet)
			String sql = "select id, name, score from student";
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				System.out.print("id:" + rs.getString("id") + " ");
				System.out.print("name:" + rs.getString("name") + " ");
				System.out.print("score:" + rs.getInt("score") + "\r\n");
			}
		}catch(SQLException e) {
			e.printStackTrace();
			
		}finally {
			try {
				stmt.close();
				rs.close();
			}catch(SQLException ex) {
				ex.printStackTrace();
			}
		}
	}
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章