Advertisement
Guest User

DB02

a guest
Apr 6th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.90 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 db01;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.sql.Statement;
  13.  
  14. /**
  15. *
  16. * @author studente
  17. */
  18. public class DB02 {
  19.  
  20. /**
  21. * @param args the command line arguments
  22. */
  23. public static void main(String[] args) {
  24.  
  25. Connection con = null;
  26. Statement stmt = null;
  27. ResultSet rs = null;
  28.  
  29. try {
  30. //apro la connessione con DB di tipo mysql usando il JDBC eindicando
  31. //user e password per la connessione
  32. con = DriverManager.getConnection(
  33. "jdbc:mysql://localhost/dbtest?user=utente1&password=utente1",
  34. "utente1",
  35. "utente1");
  36.  
  37. //ottengo lo statement per eseguire la query
  38. stmt = con.createStatement();
  39.  
  40. //preparo la query di insert
  41. String sql =" INSERT INTO `clienti`"
  42. + " (`id`, `nome`, `piva`, `indirizzo`)"
  43. + " VALUES (NULL, 'Alfio', '12345', 'Via di Qua')";
  44.  
  45. //eseguo la query di un insert e memorizzo il numero di recod modificati in num di tipo INT
  46. int num = stmt.executeUpdate(sql);
  47. //stampo il numero dei record modificati
  48. System.out.println("il numero di record modificati è " + num + ".");
  49.  
  50. rs = stmt.executeQuery("SELECT * FROM clienti");
  51.  
  52. while (rs.next()) {
  53. long id = rs.getLong("id");
  54. String nome = rs.getString("nome");
  55. //stampo tutti gli id e i nomi presesenti nel db
  56. System.out.println("ID = " + id + " Nome = " + nome);
  57. }
  58. } catch (SQLException ex) {
  59. // ex.printStackTrace();
  60. System.out.println("si è verificato un errore nell'accesso al DB");
  61. //return;
  62. //throw new Exception();
  63. } finally {
  64. if (rs != null) {
  65. try {
  66. rs.close();
  67. } catch (SQLException ex) {
  68. System.out.println("non gestita");
  69. }
  70. }
  71.  
  72. if (stmt != null) {
  73. try {
  74. stmt.close();
  75. } catch (SQLException ex) {
  76. System.out.println("non gestita");
  77. }
  78. }
  79. if (con != null) {
  80. try {
  81. con.close();
  82. } catch (SQLException ex) {
  83. System.out.println("non gestita");
  84. }
  85. }
  86. }
  87. }
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement