Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package db01;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- /**
- *
- * @author studente
- */
- public class DB02 {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- Connection con = null;
- Statement stmt = null;
- ResultSet rs = null;
- try {
- //apro la connessione con DB di tipo mysql usando il JDBC eindicando
- //user e password per la connessione
- con = DriverManager.getConnection(
- "jdbc:mysql://localhost/dbtest?user=utente1&password=utente1",
- "utente1",
- "utente1");
- //ottengo lo statement per eseguire la query
- stmt = con.createStatement();
- //preparo la query di insert
- String sql =" INSERT INTO `clienti`"
- + " (`id`, `nome`, `piva`, `indirizzo`)"
- + " VALUES (NULL, 'Alfio', '12345', 'Via di Qua')";
- //eseguo la query di un insert e memorizzo il numero di recod modificati in num di tipo INT
- int num = stmt.executeUpdate(sql);
- //stampo il numero dei record modificati
- System.out.println("il numero di record modificati è " + num + ".");
- rs = stmt.executeQuery("SELECT * FROM clienti");
- while (rs.next()) {
- long id = rs.getLong("id");
- String nome = rs.getString("nome");
- //stampo tutti gli id e i nomi presesenti nel db
- System.out.println("ID = " + id + " Nome = " + nome);
- }
- } catch (SQLException ex) {
- // ex.printStackTrace();
- System.out.println("si è verificato un errore nell'accesso al DB");
- //return;
- //throw new Exception();
- } finally {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException ex) {
- System.out.println("non gestita");
- }
- }
- if (stmt != null) {
- try {
- stmt.close();
- } catch (SQLException ex) {
- System.out.println("non gestita");
- }
- }
- if (con != null) {
- try {
- con.close();
- } catch (SQLException ex) {
- System.out.println("non gestita");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement