JDBC Insert Record

The Tutorial wants to explain a code that describe a JDBC
Insert Record. In this code we have a class JdbcInsertRecord.Inside this
class we load a driver by calling class.forName( ) that accept driver
class as argument. The Driver Manager calls getConnection ( ),which
returns a connection object. This help in built a connection between url
and database. In JDBC,Statement object perform an insert record
using batch updates. The createStatement ( ) return you a
statement object, that is used to send and execute sql statements in the database. We
can send multiple sql statement to an empty array and execute them as a batch.
The Auto commit can be disable by using setAutoCommit (false), while trying
to updates the batches. The setAutoCommit ( false) provides you a rollback of
the entire transaction, Incase any SQL statement fail during the execution
of batch update. The three INSERT statements are added to the batch, using
the addBatch ( ) method. The executeBatch ( ) return you the
update counts of arrays, this means the total number of rows affected when
sql statement is processed. Finally the execute Query ( ) return
you the record set from a table. next ( ) -
This method is used to return you the next series element in
the table. Finally the println print the required Insert record out put as
specified. Incase the exception exists in try block, the subsequent catch
block caught and handle the exception.
JdbcInsertRecord.java
import java.sql.*;
public class JdbcInsertRecord {
public static void main(String args[]) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/komal" , "root", "root");
con.setAutoCommit(false);// Disables auto-commit.
st = con.createStatement();
st.addBatch("INSERT INTO stu VALUES('1','Komal')");
st.addBatch("INSERT INTO stu VALUES('2','Ajay')");
st.addBatch("INSERT INTO stu VALUES('3','Santosh')");
st.executeBatch();
String sql = "select * from stu";
rs = st.executeQuery(sql);
System.out.println("No \tName");
while (rs.next()) {
System.out.print(rs.getString(1) + " \t");
System.out.println(rs.getString(2));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output
No Name
1 Komal
2 Ajay
3 Santosh
|
Download code

|