Guest User

Untitled

a guest
Jul 30th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. mysql dabase url, username and password in file
  2. Properties config = new Properties();
  3. config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
  4.  
  5. String url = config.getProperty("url");
  6. String username = config.getProperty("username");
  7. String password = config.getProperty("password");
  8. // ...
  9.  
  10. /**
  11. * Function that connects to a DB and data fro connection is loaded from a properties file
  12. * @param fileName
  13. * @return the connection to DB or null if any problem
  14. */
  15. public java.sql.Connection connect_to_database_from_properties(String fileName)
  16. {
  17. Properties prop = new Properties();
  18.  
  19. InputStream is;
  20. try {
  21. is = new FileInputStream(fileName);
  22.  
  23. prop.load(is);
  24. String url=prop.getProperty("url");
  25. String un=prop.getProperty("username");
  26. String pass=prop.getProperty("password");
  27. System.out.println("URL: "+url+" UN: "+un+" PASS: "+pass);
  28. is.close();
  29. Class.forName("com.mysql.jdbc.Driver");
  30.  
  31. java.sql.Connection conection =DriverManager.getConnection(url, un, pass);
  32. return conection;
  33.  
  34. } catch (FileNotFoundException e) {
  35. // TODO Auto-generated catch block
  36. e.printStackTrace();
  37. } catch (IOException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. } catch (ClassNotFoundException e) {
  41. // TODO Auto-generated catch block
  42. e.printStackTrace();
  43. } catch (SQLException e) {
  44. // TODO Auto-generated catch block
  45. e.printStackTrace();
  46. }
  47. return null;
  48.  
  49. }
Add Comment
Please, Sign In to add comment