Question #5048

write down a JDBC program to update or insert a record into a database using JDBC connection in java

Expert's answer

Task

write down a JDBC program to update or insert a record into a database using JDBC connection in java

Solution

import java.sql.*;


public class JDBCDemo {
    Connection conn;
    public static void main(String[] args) {
        new JDBCDemo();
    }
    public JDBCDemo() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String url = "jdbc:mysql://myhost/mybase";
            conn = DriverManager.getConnection(url, "username", "password");
            doTests();
            conn.close();
        } catch (ClassNotFoundException ex) {
            System.err.println(ex.getMessage());
        } catch (IllegalAccessException ex) {
            System.err.println(ex.getMessage());
        } catch (InstantiationException ex) {
            System.err.println(ex.getMessage());
        } catch (SQLException ex) {
            System.err.println(ex.getMessage());
        }
    }
}
private void doTests() {
    doSelectTest();
    doInsertTest();
    doSelectTest();
    doUpdateTest();
    doSelectTest();
    doDeleteTest();
    doSelectTest();
}
private void doSelectTest() {
    System.out.println("[OUTPUT FROM SELECT]");
    String query = "SELECT {table_field}, {table_field} FROM {mytable}";
    try {
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(query);
        String s = rs.getString("table_field");
        float n = rs.getFloat("table_field");
        System.out.println(s + " " + n);
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
}
private void doInsertTest() {
    System.out.print("\n[Performing INSERT] ... ");
    try {
        Statement st = conn.createStatement();
        st.executeUpdate("INSERT INTO {mytable} " + "VALUES ('SomeName', 200, 7.99, 0, 0)");
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
}
private void doUpdateTest() {
    System.out.print("\n[Performing UPDATE] ... ");
    try {
        Statement st = conn.createStatement();
        st.executeUpdate("UPDATE {mytable} SET {table_field} = 4.99 WHERE {table_field} = 'SomeName'");
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
}
private void doDeleteTest() {
    System.out.print("\n[Performing DELETE] ... ");
    try {
        Statement st = conn.createStatement();
        st.executeUpdate("DELETE FROM {mytable} WHERE {table_field} = 'SomeName'");
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
}
}


Answer

[OUTPUT FROM SELECT]

{table_field} cost

{table_field} cost

{table_field} cost

{table_field} cost

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS