1. 程式人生 > >Java 通過JDBC連線Mysql資料庫的方法和例項

Java 通過JDBC連線Mysql資料庫的方法和例項

  之前有兩篇文章講了安裝mysql(ubuntu和windows)和視覺化工具workbench的使用,這篇文章就講一下java程式是如何連線MySQL資料庫的。

 Java是通過JDBC連線Mysql資料庫的。JDBC(Java Data Base Connectivity,java資料庫連線)是一種用於執行SQL語句的Java API,可以為多種關係資料庫提供統一訪問,它由一組用Java語言編寫的類和介面組成。JDBC提供了一種基準,據此可以構建更高階的工具和介面,使資料庫開發人員能夠編寫資料庫應用程式

如果要使用資料庫就要新增資料庫的驅動,不同的資料庫有不用的驅動,這裡就不一一說明,新增jar程式驅動包的方法就不在這裡解釋,

下面是一個例項去介紹mysql資料庫的連線,其它資料庫的方法也是差不多的。

import java.sql.*;
public class MysqlTest {
	public static void main(String[] args){
               // 驅動程式名      
		String driver = "com.mysql.jdbc.Driver";
               // URL指向要訪問的資料庫名world      
		String url = "jdbc:mysql://127.0.0.1:3306/world";
               // MySQL配置時的使用者名稱         
		String user = "root";         
		// MySQL配置時的密碼        
		String password = "123456";
		String name;
                try {             
        	     // 載入驅動程式      
        	    Class.forName(driver);
                    // 連續資料庫     
        	   Connection conn = DriverManager.getConnection(url, user, password);
                   if(!conn.isClosed())        
        	      System.out.println("Succeeded connecting to the Database!");
                  // statement用來執行SQL語句           
                     Statement statement = conn.createStatement();
                 // 要執行的SQL語句         
                   String sql = "select * from city";
                // 結果集     
                  ResultSet rs = statement.executeQuery(sql);
                while(rs.next())  {       
        	   // 選擇Name這列資料   
        	   name = rs.getString("Name");
                  // 輸出結果            
                  System.out.println(rs.getString("CountryCode") + "\t" + name);         
             }
         rs.close();       conn.close();  } 
        catch(ClassNotFoundException e) {
         System.out.println("Sorry,can`t find the Driver!");            
         e.printStackTrace();
        } catch(SQLException e) {
         e.printStackTrace();
        } catch(Exception e) {
         e.printStackTrace();
        } 
        }
}

Note:如果你沒有新增jar程式驅動包的話編譯的時候發現以下問題:

Sorry,can`t find the Driver!

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

    atjava.net.URLClassLoader$1.run(Unknown Source)

    atjava.net.URLClassLoader$1.run(Unknown Source)

    atjava.security.AccessController.doPrivileged(Native Method)

    atjava.net.URLClassLoader.findClass(Unknown Source)

    atjava.lang.ClassLoader.loadClass(Unknown Source)

    atsun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

    atjava.lang.ClassLoader.loadClass(Unknown Source)

    atjava.lang.Class.forName0(Native Method)

     atjava.lang.Class.forName(Unknown Source)


但是編譯執行雖然成功,但是有以下的warning資訊:

Thu Dec 24 00:08:37 CST 2015WARN: Establishing SSL connection without server's identity verification is notrecommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSLconnection must be established by default if explicit option isn't set. Forcompliance with existing applications not using SSL the verifyServerCertificateproperty is set to 'false'. You need either to explicitly disable SSL bysetting useSSL=false, or set useSSL=true and provide truststore for servercertificate verification.

Succeeded connecting to theDatabase!

AFG Kabul

AFG Qandahar

AFG Herat

AFG Mazar-e-Sharif

NLD Amsterdam

NLD Rotterdam

NLD Haag

這時只需要把url字串改為以下:

改之前:String url ="jdbc:mysql://127.0.0.1:3306/world";

改之後:String url = "jdbc:mysql://127.0.0.1:3306/world?useUnicode=true&characterEncoding=utf-8&useSSL=false";

就發現warning沒了,程式執行成功。

Succeeded connecting to theDatabase!

AFG Kabul

AFG Qandahar

AFG Herat

AFG Mazar-e-Sharif

NLD Amsterdam

NLD Rotterdam

NLD Haag

NLD                                 Utrecht