Advertisement
Guest User

Untitled

a guest
Apr 27th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. package test2;
  2. import java.sql.*;
  3. import java.util.Properties;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;
  11.  
  12. public class ConnectingToMysqlGoogleCloud {
  13.  
  14. public static void main (String[] args) throws Exception
  15. {
  16. // Initialize connection variables.
  17. String host = "35.197.211.160";
  18. String database = "quickstartdb";
  19. String user = "root";
  20. String password = "Dapolice1";
  21. String query = "SELECT * FROM inventory";
  22.  
  23. // check that the driver is installed
  24. try
  25. {
  26. Class.forName("com.mysql.jdbc.Driver");
  27. }
  28. catch (ClassNotFoundException e)
  29. {
  30. throw new ClassNotFoundException("MySQL JDBC driver NOT detected in library path.", e);
  31. }
  32.  
  33. System.out.println("MySQL JDBC driver detected in library path.");
  34.  
  35. Connection connection = null;
  36.  
  37. // Initialize connection object
  38. try
  39. {
  40. //String url = String.format("jdbc:mysql://%s:3306/%s", host, database);
  41. String url = String.format("jdbc:mysql://google/%s?cloudSqlInstance=%s&socketFactory=com.google.cloud.sql.mysql.SocketFactory", "quickstartdb", "master-smithy-202216:europe-west2:fagprojekt");
  42. // Set connection properties.
  43. Properties properties = new Properties();
  44. properties.setProperty("user", user);
  45. properties.setProperty("password", password);
  46. properties.setProperty("useSSL", "true");
  47. properties.setProperty("verifyServerCertificate", "true");
  48. properties.setProperty("requireSSL", "false");
  49.  
  50. // get connection
  51. connection = DriverManager.getConnection(url, properties);
  52. }
  53. catch (SQLException e)
  54. {
  55. throw new SQLException("Failed to create connection to database.", e);
  56. }
  57. if (connection != null) {
  58. while (connection != null) {
  59. System.out.println("Successfully created connection to database.");
  60. Statement st = connection.createStatement();
  61. ResultSet rs = st.executeQuery(query);
  62. if (rs.next()) {
  63. System.out.println(rs.getInt(3));
  64. }
  65. Thread.sleep(5000);
  66. }
  67. }
  68. else {
  69. System.out.println("Failed to create connection to database.");
  70. }
  71. System.out.println("Execution finished.");
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement