Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test2;
- import java.sql.*;
- import java.util.Properties;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class ConnectingToMysqlGoogleCloud {
- public static void main (String[] args) throws Exception
- {
- // Initialize connection variables.
- String host = "35.197.211.160";
- String database = "quickstartdb";
- String user = "root";
- String password = "Dapolice1";
- String query = "SELECT * FROM inventory";
- // check that the driver is installed
- try
- {
- Class.forName("com.mysql.jdbc.Driver");
- }
- catch (ClassNotFoundException e)
- {
- throw new ClassNotFoundException("MySQL JDBC driver NOT detected in library path.", e);
- }
- System.out.println("MySQL JDBC driver detected in library path.");
- Connection connection = null;
- // Initialize connection object
- try
- {
- //String url = String.format("jdbc:mysql://%s:3306/%s", host, database);
- String url = String.format("jdbc:mysql://google/%s?cloudSqlInstance=%s&socketFactory=com.google.cloud.sql.mysql.SocketFactory", "quickstartdb", "master-smithy-202216:europe-west2:fagprojekt");
- // Set connection properties.
- Properties properties = new Properties();
- properties.setProperty("user", user);
- properties.setProperty("password", password);
- properties.setProperty("useSSL", "true");
- properties.setProperty("verifyServerCertificate", "true");
- properties.setProperty("requireSSL", "false");
- // get connection
- connection = DriverManager.getConnection(url, properties);
- }
- catch (SQLException e)
- {
- throw new SQLException("Failed to create connection to database.", e);
- }
- if (connection != null) {
- while (connection != null) {
- System.out.println("Successfully created connection to database.");
- Statement st = connection.createStatement();
- ResultSet rs = st.executeQuery(query);
- if (rs.next()) {
- System.out.println(rs.getInt(3));
- }
- Thread.sleep(5000);
- }
- }
- else {
- System.out.println("Failed to create connection to database.");
- }
- System.out.println("Execution finished.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement