Java, JDBC, Oracle

Oracle database connection in Java

Here is an example to show how to connect to Oracle database in Java.

The Oracle JDBC driver can be downloaded from here. The download contains a JAR file which you need to add to your classpath.

Here is the code to connect to Oracle database in Java:

    public Connection getOracleConnection() {
    	
    	// If connecting using Service Name
    	String url = "jdbc:oracle:thin:@//YourHostName:1521/YourServiceName";
    	
    	// If connecting using SID
    	//String url = "jdbc:oracle:thin:@//YourHostName:1521:YourSID";
    	
		String username = "YourUsername";
		String password = "YourPassword";
		Connection conn = null;
		
    	try {
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		
    		try {
    			conn = DriverManager.getConnection(url, username, password);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	} catch (ClassNotFoundException e) {
    		e.printStackTrace();
    	}

    	return conn;
    }
Java, JDBC, Maven, MySQL

MySQL Connection in Java

Here is an example to show how to connect to MySQL database in Java.

First things first. If you are using Maven, please add the MySQL dependency in your pom.xml file. The dependency looks like this:

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.25</version>
		</dependency>

If you are NOT using Maven, you need to download the MySQL JDBC driver. The driver can be found here. The download contains a JAR file which you need to add to your classpath.

That is it! Here is the code to connect to MySQL database in Java:

    public Connection getMySqlConnection() {
    	
    	String url = "jdbc:mysql://YourHostName:3306/";
		String database = "YourDatabaseName";
		String username = "YourUsername";
		String password = "YourPassword";
		Connection conn = null;
		
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    		
    		try {
    			conn = DriverManager.getConnection(url+database, username, password);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	} catch (ClassNotFoundException e) {
    		e.printStackTrace();
    	}

    	return conn;
    }