prateeksharma

JDBC

Dec 5th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. package connection;
  2.  
  3.  
  4. //import java.sql.DriverManager;
  5. import java.sql.*;
  6.  
  7. public class StudentConnection {
  8. Connection con;
  9. StudentConnection(){
  10. try{
  11. Class.forName("com.mysql.cj.jdbc.Driver");
  12. System.out.println("Connecting to Database...");
  13. String connectionURL = "jdbc:mysql://localhost:3306/student";
  14. con = DriverManager.getConnection(connectionURL,"root","");
  15. System.out.println("Connection to Database successfully...");
  16. }
  17. catch (ClassNotFoundException e){
  18. e.printStackTrace();
  19. }
  20. catch (SQLException e){
  21. e.printStackTrace();
  22. }
  23. }
  24.  
  25. public static void main(String[] args) {
  26. StudentConnection obj = new StudentConnection();
  27. }
  28. }
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35. package connection;
  36.  
  37. import java.sql.*;
  38.  
  39. public class DatabaseHelper extends StudentConnection{
  40.  
  41. void insert(){
  42. try{
  43. //Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
  44. String insert_query = "insert into Student values(04,'vijay','BBA',2017)";
  45. PreparedStatement preparedStatement = con.prepareStatement(insert_query);
  46. int a= preparedStatement.executeUpdate();
  47. insert_query = "insert into Student values(01,'prateek','CSE',2018)";
  48. a += preparedStatement.executeUpdate(insert_query);
  49. System.out.println("Data inserted by affecting "+a+" row");
  50. }
  51. catch (Exception e){
  52. System.out.println(e);
  53. }
  54. }
  55.  
  56. void view(){
  57. String view_query = "select * from Student";
  58. try{
  59. PreparedStatement preparedStatement = con.prepareStatement(view_query);
  60. ResultSet resultSet = preparedStatement.executeQuery(view_query);
  61.  
  62. while(resultSet.next()){
  63. System.out.print(" "+resultSet.getInt("studentID"));
  64. System.out.print(" "+resultSet.getString("studentName"));
  65. System.out.print(" "+resultSet.getString("studentCourse"));
  66. System.out.print(" "+resultSet.getInt("year"));
  67. System.out.println("\n");
  68.  
  69. }
  70. System.out.println("Data Found");
  71. }
  72. catch (Exception e){
  73. System.out.println(e);
  74. }
  75. }
  76.  
  77. void delete(){
  78.  
  79. }
  80.  
  81. public static void main(String[] args) {
  82. DatabaseHelper obj = new DatabaseHelper();
  83. obj.insert();
  84. obj.view();
  85. }
  86.  
  87. }
Add Comment
Please, Sign In to add comment