Guest User

Untitled

a guest
Feb 16th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package mysqlconnect;
  7.  
  8. /**
  9. *
  10. * @author Jami
  11. */
  12.  
  13. import java.sql.*;
  14. import java.util.Scanner;
  15.  
  16. public class DBConnect {
  17.  
  18. private Connection con;
  19. private Statement st;
  20. private ResultSet rs;
  21.  
  22. public DBConnect(){
  23. try{
  24. Class.forName("com.mysql.jdbc.Driver");
  25.  
  26. con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
  27. /*localhost = hostname, 3306 = portnumber, user = databasename, root = databaseusername...
  28. no need of password write now...*/
  29. st = con.createStatement();
  30.  
  31. }
  32. catch(Exception ex){
  33. System.out.println("Error: "+ex);
  34. }
  35. }
  36.  
  37.  
  38. public void insertData(){
  39. String name="",pas="";
  40. Scanner sc = new Scanner(System.in);
  41. System.out.print("User name: ");
  42. name = sc.next();
  43. System.out.print("Password: ");
  44. pas = sc.next();
  45.  
  46. try{
  47. PreparedStatement inserted = con.prepareStatement("INSERT INTO INFO(name,password)VALUES('"+name+"','"+pas+"')");
  48. inserted.executeUpdate();
  49. }
  50. catch(Exception ex){
  51. System.out.println(ex);
  52. }
  53. }
  54.  
  55.  
  56. public void getdata(){
  57.  
  58. try{
  59. String q = "select * from info";
  60. rs = st.executeQuery(q);
  61. System.out.println("Record");
  62. while(rs.next()){
  63. String n = rs.getString("name");
  64. String p = rs.getString("password");
  65. int i = rs.getInt("id");
  66. System.out.println("ID: "+i+" "+"Name: "+n+ " "+"Password: "+p);
  67.  
  68. }
  69. }
  70. catch(Exception ex){
  71. System.out.println(ex);
  72. }
  73.  
  74. }
  75.  
  76. public void deleteData(){
  77. Scanner sc = new Scanner(System.in);
  78. int i = sc.nextInt();
  79.  
  80. try{
  81. PreparedStatement deleted = con.prepareStatement("DELETE FROM INFO WHERE id = '"+i+"'");
  82. deleted.executeUpdate();
  83. }
  84. catch(Exception ex){
  85. System.out.println(ex);
  86. }
  87. }
  88.  
  89. }
Add Comment
Please, Sign In to add comment