Advertisement
VipulKumar13

Java Database Connection

Aug 21st, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. //You have to add "mysql-connector-java.jar" library
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.Scanner;
  9.  
  10. public class SQL_Sample_1 {
  11.  
  12.     /**
  13.      * @param args the command line arguments
  14.      */
  15.     public static void main(String[] args) {
  16.         Scanner input = new Scanner(System.in);
  17.         String verbo = "";
  18.         System.out.println("SCRIVIMI UN VERBO ED IO TI DARO' IL SINONIMO");
  19.         verbo = input.nextLine();
  20.        
  21.         try {
  22.             Class.forName("com.mysql.jdbc.Driver");
  23.         } catch (ClassNotFoundException ex) { ex.printStackTrace(); }
  24.         Connection conn = null;
  25.         try {
  26.             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseName", "root", ""); //Connecting to the database
  27.         }
  28.         catch (SQLException ex) { ex.printStackTrace(); }
  29.        
  30.     Statement stmt = null;
  31.         try { stmt = conn.createStatement();}
  32.         catch (SQLException ex) { ex.printStackTrace(); }
  33.        
  34.     String query = "select azione.Azione"
  35.                      + " from sinonimo inner join azione on sinonimo.CodiceAzione = azione.Codice"
  36.                      + " where sinonimo = '" + verbo + "'";
  37.        
  38.     //Executing the query
  39.     try {
  40.             ResultSet rs = stmt.executeQuery(query);
  41.         //Fetching results
  42.             while(rs.next())
  43.             {
  44.                 String azione = rs.getString("azione");
  45.                 System.out.println(azione);
  46.             }
  47.         } catch (SQLException ex) { ex.printStackTrace(); }
  48.     }
  49.    
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement