第一步必須先至MySQL網站下載 Connect/J的mysql-connector-java-*-bin.jar

接著加入java的classpath

root# export CLASSPATH=$CLASSPATH:完整路徑/mysql-connector-java-*-bin.jar

(*號請自行替代版本號,另外加入CLASSPATH時記得前面要補上$CLASSPATH,不然整個CLASSPATH會被mysql-connector-java-*-bin.jar蓋掉,導致java程式無法執行)

import java.sql.*;

public class JavaToMysql 
{ 
	private static Connection dbCon = null; 
	private static Statement stmt = null; 
	private static ResultSet rs = null; 
	public static void main(String [] arg) 
	{ 
		try 
		{ 
			Class.forName("com.mysql.jdbc.Driver").newInstance(); 
			System.out.println("載入驅動程式成功"); 
		}
		catch (Exception e) 
		{ 
			System.out.println("無法載入驅動程式"); 
		} 
		try 
		{ 
			dbCon = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/database_name?user=root&password=1234"); 
			stmt = dbCon.createStatement(); 
			if(stmt==null)  {System.out.println("stmt==null : 無法連結MYSQL資料庫");} 
			else System.out.println("連結MYSQL資料庫成功"); 
		}
		catch (SQLException e) 
		{ 
			System.out.println("SQLException : 無法連結MYSQL資料庫"); 
		} 
		try 
		{
			//SELECT 使用的是executQuery,回傳的是ResultSet
			rs = stmt.executeQuery("select * from demodb"); 
			while (rs.next()) 
			{ 
				System.out.println(rs.getString("欄位").trim());  //抓取資料庫中的資料印出來,trim為忽略前後空白
			} 
			
			//INSERT UPDATE 等是利用executeUpdate,回傳值為int
			stmt.executeUpdate("INSERT INTO demodb values('')");
		}
		catch (SQLException e) 
		{ 
			e.printStackTrace(); 
		} 
	} 
} 
Categories: Java