Jdbc Insert Statement


Jdbc Insert Statement

The Tutorial give you an example from JDBC Insert Statement.

The Tutorial give you an example from JDBC Insert Statement.

JDBC Insert Statement


Add a row to a existing table using insert statement in JDBC. The tutorial illustrates an example from JDBC Insert Statement. In this program, the code include a class Jdbc Insert Statement. Inside this class we have a list of method that help you to insert the new values to the existing table as given below -

Loading a driver by calling a class.forName( ),that accept driver class as parameter. The DriverManager.getConnection ( ) returns you a connection object, which built a connection between url and database. The connection object calls createStatement ( ),that returns you a sql object. This object send and execute sql statements in database. To add a rows in an existing table, we use INSERT statement.

   executeUpdate ( ) -  This method returns you the number of rows added and modified  in a table.

The interface statement object ,st,executes the INSERT statement using execute Update ( ).The executeQuery ( ) return you the retrieved record set  from a table using select statement Finally the print ln print no, name from the table. Incase there is an exception in try block, the catch block caught and handle the exception



import java.sql.*;

public class JdbcInsertStatement {

    public static void main(String args[]) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/";
        String db = "komal";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "root";
        try {
            con = DriverManager.getConnection(url + db, user, pass);
            con.setAutoCommit(false);// Disables auto-commit.

            st = con.createStatement();

            st.executeUpdate("INSERT INTO stu VALUES('1','Komal')");
            st.executeUpdate("INSERT INTO stu VALUES('2','Ajay')");
            st.executeUpdate("INSERT INTO stu VALUES('3','Santosh')");
            st.executeUpdate("INSERT INTO stu VALUES('4','Girish')");
            st.executeUpdate("INSERT INTO stu VALUES('5','Rakesh')");


            String sql = "select * from stu";
            rs = st.executeQuery(sql);

            System.out.println("No  \tName");
            while (rs.next()) {
                System.out.print(rs.getString(1) + "   \t");
        } catch (Exception e) {



No  	Name
1   	Komal
2   	Ajay
3   	Santosh
4   	Girish
5   	Rakesh

Download code