Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. package toka;
  2. import java.sql.*;
  3. import java.util.Scanner;
  4.  
  5. public class Test {
  6. static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
  7. //static final String DB_URL = "jdbc:mariadb://localhost/db20";
  8. static final String DB_URL = "jdbc:mysql://localhost/db20?";
  9. // Database credentials
  10. static final String USER = "mikko20";
  11. static final String PASS = "kt123456";
  12.  
  13. public static void main(String[] args) {
  14. Connection conn = null;
  15. Statement stmt = null;
  16. try {
  17. //STEP 2: Register JDBC driver
  18. Class.forName(JDBC_DRIVER);
  19. System.out.println("Connecting to a selected database...");
  20. /*conn = DriverManager.getConnection(
  21. DB_URL, USER, PASS);*/
  22. conn = DriverManager.getConnection(
  23. DB_URL + "user=" + USER + "&password=" + PASS);
  24. System.out.println("Connected database successfully...");
  25. stmt = conn.createStatement();
  26. Scanner scan = new Scanner(System.in);
  27. int idr = 0;
  28. System.out.println("Anna id");
  29. idr = scan.nextInt();
  30. String etunimi;
  31. System.out.println("Anna etunimi: ");
  32. etunimi = scan.next();
  33. String sukunimi;
  34. System.out.println("Anna sukunimi: ");
  35. sukunimi = scan.next();
  36. System.out.println("Anna ikä");
  37. int ika = scan.nextInt();
  38.  
  39. String sqlInsert = "INSERT INTO REGISTRATION VALUES(";
  40. sqlInsert += String.valueOf(idr);
  41. sqlInsert += ",'";
  42. sqlInsert += etunimi;
  43. sqlInsert += "','";
  44. sqlInsert += sukunimi;
  45. sqlInsert += "',";
  46. sqlInsert += String.valueOf(ika);
  47. sqlInsert += ")";
  48. stmt.executeUpdate(sqlInsert);
  49. scan.close();
  50. String sql = "SELECT * FROM REGISTRATION;";
  51. ResultSet rs = stmt.executeQuery(sql); // rs olioon palautuu tietuejoukko
  52. while (rs.next())
  53. {
  54. int id = rs.getInt("id");
  55. String firstName = rs.getString("first");
  56. String lastName = rs.getString("last");
  57. int age = rs.getInt("age");
  58. // print the results
  59. System.out.format("%s, %s, %s, %s\n", id, firstName, lastName, age);
  60. }
  61. stmt.close();
  62. }
  63. catch (SQLException se) {
  64. se.printStackTrace();
  65. }
  66. catch (Exception e) {
  67. e.printStackTrace();
  68. }
  69. finally {
  70. try {
  71. if (stmt != null) {
  72. conn.close();
  73. }
  74. }
  75. catch (SQLException se) {
  76.  
  77. }
  78. try {
  79. if (conn != null) {
  80. conn.close();
  81. }
  82. } catch (SQLException se) {
  83. se.printStackTrace();
  84. }
  85. }
  86. System.out.println("Goodbye!");
  87.  
  88. }
  89.  
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement