Guest User

Untitled

a guest
Mar 14th, 2019
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6.  
  7. public class JDBCStmt {
  8.  
  9. public static void main(String[] args) {
  10. Connection connection = null;
  11. try {
  12. // Loading driver
  13. Class.forName("com.mysql.jdbc.Driver");
  14.  
  15. // Creating connection
  16. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs",
  17. "root", "admin");
  18.  
  19. // creating Statement
  20. Statement stmt = connection.createStatement();
  21.  
  22. /** execute method **/
  23. boolean flag = stmt.execute("Update Employee set age = 40 where id in (5, 6)");
  24. if(flag == false){
  25. System.out.println("Updated rows " + stmt.getUpdateCount() );
  26. }
  27.  
  28. /** executeUpdate method **/
  29. // Insert
  30. int count = stmt.executeUpdate("Insert into employee(name, age) values('Kim', 23)");
  31. System.out.println("Rows Inserted " + count);
  32.  
  33. // update
  34. count = stmt.executeUpdate("Update Employee set age = 35 where id = 17");
  35. System.out.println("Rows Updated " + count);
  36.  
  37. //delete
  38. count = stmt.executeUpdate("Delete from Employee where id = 5");
  39. System.out.println("Rows Deleted " + count);
  40.  
  41. /** executeQuery method **/
  42. // Executing Query
  43. ResultSet rs = stmt.executeQuery("Select * from Employee");
  44.  
  45. // Processing Resultset
  46. while(rs.next()){
  47. System.out.println("id : " + rs.getInt("id") + " Name : "
  48. + rs.getString("name") + " Age : " + rs.getInt("age"));
  49. }
  50.  
  51. } catch (ClassNotFoundException e) {
  52. // TODO Auto-generated catch block
  53. e.printStackTrace();
  54. } catch (SQLException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. }finally{
  58. if(connection != null){
  59. //closing connection
  60. try {
  61. connection.close();
  62. } catch (SQLException e) {
  63. // TODO Auto-generated catch block
  64. e.printStackTrace();
  65. }
  66. } // if condition
  67. }// finally
  68.  
  69. }
  70. }
Add Comment
Please, Sign In to add comment