Advertisement
Guest User

java

a guest
May 5th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Properties;
  3. import java.io.*;
  4.  
  5.  
  6. public class DBMysql
  7. {
  8. // The JDBC Connector Class.
  9. private static final String dbClassName = "com.mysql.jdbc.Driver";
  10. // Connection string. emotherearth is the database the program
  11. // is connecting to. You can include user and password after this
  12. // by adding (say) ?user=paulr&password=paulr. Not recommended!
  13.  
  14. private static final String CONNECTION =
  15. "jdbc:mysql://172.30.2.116/gestio";
  16. public static void main(String[] args)
  17. throws ClassNotFoundException,SQLException {
  18. // Class.forName(xxx) loads the jdbc classes and
  19. // creates a drivermanager class factory
  20. Class.forName(dbClassName);
  21. // Properties for user and password. Here the user and password are both 'paulr'
  22. Properties p = new Properties();
  23. p.put("user","guillem");
  24. p.put("password","guillem");
  25.  
  26. // Now try to connect
  27. Connection c = DriverManager.getConnection(CONNECTION,p);
  28. exempleSelect(c);
  29. c.close();
  30. }
  31.  
  32. private static void exempleSelect(Connection conn){
  33. try {
  34. Statement stmt = conn.createStatement();
  35. String sql = "select id_municipi,descripcio from MUNICIPI";
  36. ResultSet rs = stmt.executeQuery(sql);
  37. //STEP 5: Extract data from result set
  38. while(rs.next()){
  39. //Retrieve by column name
  40. int id_municipi = rs.getInt("id_municipi");
  41. String descripcio = rs.getString("descripcio");
  42. //Display values
  43. System.out.print("id_municipi: " + id_municipi);
  44. System.out.println(", descripcio: " + descripcio);
  45. }
  46. rs.close();
  47.  
  48. }catch(SQLException se){
  49. //Handle errors for JDBC
  50. System.out.println("error sql");
  51. se.printStackTrace();
  52.  
  53. }
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement