Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class JDBCStmt {
- public static void main(String[] args) {
- Connection connection = null;
- try {
- // Loading driver
- Class.forName("com.mysql.jdbc.Driver");
- // Creating connection
- connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs",
- "root", "admin");
- // creating Statement
- Statement stmt = connection.createStatement();
- /** execute method **/
- boolean flag = stmt.execute("Update Employee set age = 40 where id in (5, 6)");
- if(flag == false){
- System.out.println("Updated rows " + stmt.getUpdateCount() );
- }
- /** executeUpdate method **/
- // Insert
- int count = stmt.executeUpdate("Insert into employee(name, age) values('Kim', 23)");
- System.out.println("Rows Inserted " + count);
- // update
- count = stmt.executeUpdate("Update Employee set age = 35 where id = 17");
- System.out.println("Rows Updated " + count);
- //delete
- count = stmt.executeUpdate("Delete from Employee where id = 5");
- System.out.println("Rows Deleted " + count);
- /** executeQuery method **/
- // Executing Query
- ResultSet rs = stmt.executeQuery("Select * from Employee");
- // Processing Resultset
- while(rs.next()){
- System.out.println("id : " + rs.getInt("id") + " Name : "
- + rs.getString("name") + " Age : " + rs.getInt("age"));
- }
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(connection != null){
- //closing connection
- try {
- connection.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- } // if condition
- }// finally
- }
- }
Add Comment
Please, Sign In to add comment