The following code shows how to insert record to database table.
It uses the Statement
to execute the hardcoded sql commands.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; //from ww w .j a va2 s .c o m public class Main { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) throws Exception { Connection conn = null; Statement stmt = null; Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Deleting database..."); stmt = conn.createStatement(); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = "INSERT INTO Person VALUES (1, 'A', 'B', 18)"; stmt.executeUpdate(sql); sql = "INSERT INTO Person VALUES (2, 'C', 'D', 25)"; stmt.executeUpdate(sql); sql = "INSERT INTO Person VALUES (3, 'E', 'F', 30)"; stmt.executeUpdate(sql); sql = "INSERT INTO Person VALUES(4, 'S', 'M', 28)"; stmt.executeUpdate(sql); stmt.close(); conn.close(); } }
The following code shows how to insert a record using PreparedStatement
.
It is using the Oracle JDBC driver.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; /*from w ww. j a va2s . co m*/ public class Main { private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase"; private static final String DB_USER = "user"; private static final String DB_PASSWORD = "password"; public static void main(String[] argv) throws Exception { Connection dbConnection = null; PreparedStatement preparedStatement = null; Class.forName(DB_DRIVER); dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); String insertTableSQL = "INSERT INTO Person" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES" + "(?,?,?,?)"; preparedStatement = dbConnection.prepareStatement(insertTableSQL); preparedStatement.setInt(1, 11); preparedStatement.setString(2, "yourName"); preparedStatement.setString(3, "system"); java.util.Date today = new java.util.Date(); preparedStatement.setTimestamp(4, new java.sql.Timestamp(today.getTime())); preparedStatement.executeUpdate(); preparedStatement.close(); dbConnection.close(); } }