1. 程式人生 > >eclipse連線Oracle資料庫和MySQL資料庫

eclipse連線Oracle資料庫和MySQL資料庫

連線Oracle:

package test;

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

public class TestOracle {

	private static String driver="oracle.jdbc.OracleDriver";
	private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
	private static String user="scott";
	private static String password="root2306";
	
	
	public static void main(String[] args) {
		ResultSet rs=null;
		Statement statement=null;
		Connection connection=null;
		
try{
	//註冊資料庫的驅動
	Class.forName(driver);
	//獲取資料庫連線
	connection=DriverManager.getConnection(url,user,password);
	
	statement=connection.createStatement();
	rs=statement.executeQuery("select * from users");
	while(rs.next()){
		System.out.println(rs.getString("username"));
		System.out.println(rs.getString("age"));
	}
}catch(ClassNotFoundException e){
	e.printStackTrace();
	
}catch(SQLException  e){
	e.printStackTrace();
}finally{
	//釋放資料庫資源
	try{
		if(rs!=null)
		{
			rs.close();
		    rs=null;
		}if(connection!=null){
			connection.close();connection=null;
		}if(statement!=null){
			statement.close();statement=null;
		}
	}catch(SQLException e){
		e.printStackTrace();
	}
}
	}

}

}


連線MySQL:

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


public class TestMysql {
	
	private static String driver="com.mysql.jdbc.Driver";
	private static String url="jdbc:mysql://106.14.182.157:3306/test";
	private static String user="root";
	private static String password="root";

	public static void main(String[] args) {
		ResultSet rs=null;
		Statement statement=null;
		Connection connection=null;
		
try{
	//註冊資料庫的驅動
	Class.forName(driver);
	//獲取資料庫連線
	connection=DriverManager.getConnection(url,user,password);
	
	statement=connection.createStatement();
	rs=statement.executeQuery("select * from users");
	while(rs.next()){
		System.out.println(rs.getString("username"));
		System.out.println(rs.getString("age"));
	}
}catch(ClassNotFoundException e){
	e.printStackTrace();
	
}catch(SQLException  e){
	e.printStackTrace();
}finally{
	//釋放資料庫資源
	try{
		if(rs!=null)
		{
			rs.close();
		    rs=null;
		}if(connection!=null){
			connection.close();connection=null;
		}if(statement!=null){
			statement.close();statement=null;
		}
	}catch(SQLException e){
		e.printStackTrace();
	}
}
	}

}


對比一下,是不是一樣一樣滴!!!!