Advertisement
Guest User

Untitled

a guest
Oct 5th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 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 Students {
  8.  
  9. public static void main(String[] args) {
  10. Connection con = null;
  11. Statement stmt = null;
  12.  
  13. try {
  14. Class.forName("com.mysql.jdbc.Driver");
  15. String url = "jdbc:mysql://localhost:3306/studentdb";
  16. con = DriverManager.getConnection(url, "root", "12345");
  17. stmt = con.createStatement();
  18.  
  19. // insert data to studentdb
  20. int result = stmt.executeUpdate("insert into student(student_name, age) values('papat',40)");
  21. result += stmt.executeUpdate("insert into student(student_name, age) values('wannida', 30)");
  22. result += stmt.executeUpdate("insert into student(student_name, age) values('wandee', 45)");
  23. System.out.println("Inserted " + result + " row success");
  24. //Query data
  25. ResultSet rs = stmt.executeQuery("select * from student order by idstudent");
  26. while (rs.next()) {
  27. int id = rs.getInt("idstudent");
  28. String name = rs.getString("student_name");
  29. int age = rs.getInt("age");
  30. System.out.println("ID : " + id + " Name : " + name + " Age :" + age);
  31. }
  32. rs.close();
  33. } catch (ClassNotFoundException ex1) {
  34. ex1.printStackTrace();
  35. } catch (SQLException ex2) {
  36. ex2.printStackTrace();
  37. } catch (Exception ex3) {
  38. ex3.printStackTrace();
  39. } finally {
  40. try {
  41. if (stmt != null) {
  42. stmt.close();
  43. }
  44. if (con != null) {
  45. con.close();
  46. }
  47. } catch (SQLException err) {
  48. err.printStackTrace();
  49. }
  50. }
  51.  
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement