connection in java code example
Example 1: java connect to mysql
import java.sql.*;
class MySqlConn{
public static void main(String args[]){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://
localhost:3306/databasename","username","password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
con.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
Example 2: create jdbc connection in java
package com.java2novice.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConnection {
public static void main(String a[]){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.
getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}