Java database connectivity steps
What is difference between statement and preparedstatement in java ?
In the previous jdbc tutorial named as types of jdbc drivers in java we learned about what is jdbc in java and jdbc drivers in java . Now in this jdbc tutorial we will learn how to create jdbc connection in java or java database connectivity with mysql or jdbc connection in java with oracle.
- Create an ODBC Data Source Name.
- Register the Driver class or load the jdbc drivers in java
- Create a connection
- Create statement and execute query.
- Loop the result set until the data is available in table
- Free resources or Close connection
To connect with MySql – Class.forName (“org.gjt.mm.mysql.Driver”);
Jdbc connection in java with Oracle – Class.forName (“oracle.jdbc.driver.OracleDriver”);
Jdbc connection with SqlServer Class.forName (“com.microsoft.jdbc.sqlserver.SQLServerDriver”);
Step 2 – Create a connection
here jdbcURL syntax is written as jdbc:odbc:dsnName
Difference between PreparedStatement and Statement
Create table using PreparedStatement JDBC
Class : JDBCTest.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.computersciencejunction.util.JDBCUtil;
/**
* This class is used to create a table in DB
* using PreparedStatement.
* @author computersciencejunction
*/
public class JDBCTest {
public static void main(String args[]){
Connection conn = null;
PreparedStatement preparedStatement = null;
String query = “create table EMPLOYEE(”
+ “EMPLOYEE_ID NUMBER(5) NOT NULL, ”
+ “NAME VARCHAR(20) NOT NULL, ”
+ “SALARY NUMBER(10) NOT NULL, ”
+ “PRIMARY KEY (EMPLOYEE_ID) )”;
try{
//get connection
conn = JDBCUtil.getConnection();
//create preparedStatement
preparedStatement = conn.preparedStatement(query);
//execute query
preparedStatement.execute();
//close connection
preparedStatement.close();
conn.close();
System.out.println(“Table created successfully.”);
}catch(Exception e){
e.printStackTrace();
}
}
}
Class JDBCUtil.java
import java.sql.Connection;
import java.sql.DriverManager;
/**
* This is a utility class for JDBC connection.
* @author computersciencejunction
*/
public class JDBCUtil {
//JDBC and database properties.
private static final String DB_DRIVER =
“oracle.jdbc.driver.OracleDriver”;
private static final String DB_URL =
“jdbc:oracle:thin:@localhost:1521:XE”;
private static final String DB_USERNAME = “system”;
private static final String DB_PASSWORD = “oracle”;
public static Connection getConnection(){
Connection conn = null;
try{
//Register the JDBC driver
Class.forName(DB_DRIVER);
//Open the connection
conn = DriverManager.
getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
if(conn != null){
System.out.println(“Successfully connected.”);
}else{
System.out.println(“Failed to connect.”);
}
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}
Output
Successfully connected.
Table created successfully