0

我試圖與雲端SQL連接,但它始終顯示錯誤。無法與Google Cloud建立連接SQL

HTTP ERROR 500 

Problem accessing /cloudsql. Reason: 

    Could not create connection to database server. 
Caused by: 

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:140) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:148) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) 
    at com.mysql.jdbc.Util.getInstance(Util.java:408) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) 
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2330) 
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083) 
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806) 
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:140) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:148) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) 
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410) 
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328) 
    at java.sql.DriverManager.getConnection(DriverManager.java:664) 
    at java.sql.DriverManager.getConnection(DriverManager.java:270) 
    at com.azeem.endpoint.CloudSqlServlet.doGet(CloudSqlServlet.java:70) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) 
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) 
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) 
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) 
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) 
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) 
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:95) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:508) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at org.mortbay.jetty.Server.handle(Server.java:326) 
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) 
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) 
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547) 
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) 
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) 
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409) 
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) 
Caused by: java.lang.RuntimeException: Unable to obtain credentials to communicate with the Cloud SQL API 
    at com.google.cloud.sql.core.SslSocketFactory$ApplicationDefaultCredentialFactory.create(SslSocketFactory.java:547) 
    at com.google.cloud.sql.core.SslSocketFactory.getInstance(SslSocketFactory.java:140) 
    at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:48) 
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300) 
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251) 
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284) 
    ... 52 more 
Caused by: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. 
    at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:95) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191) 
    at com.google.cloud.sql.core.SslSocketFactory$ApplicationDefaultCredentialFactory.create(SslSocketFactory.java:545) 
    ... 57 more 
Caused by: 

java.lang.RuntimeException: Unable to obtain credentials to communicate with the Cloud SQL API 
    at com.google.cloud.sql.core.SslSocketFactory$ApplicationDefaultCredentialFactory.create(SslSocketFactory.java:547) 
    at com.google.cloud.sql.core.SslSocketFactory.getInstance(SslSocketFactory.java:140) 
    at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:48) 
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300) 
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251) 
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284) 
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083) 
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806) 
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:140) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:148) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) 
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410) 
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328) 
    at java.sql.DriverManager.getConnection(DriverManager.java:664) 
    at java.sql.DriverManager.getConnection(DriverManager.java:270) 
    at com.azeem.endpoint.CloudSqlServlet.doGet(CloudSqlServlet.java:70) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) 
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) 
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) 
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) 
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) 
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) 
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:95) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:508) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at org.mortbay.jetty.Server.handle(Server.java:326) 
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) 
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) 
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547) 
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) 
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) 
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409) 
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) 
Caused by: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. 
    at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:95) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191) 
    at com.google.cloud.sql.core.SslSocketFactory$ApplicationDefaultCredentialFactory.create(SslSocketFactory.java:545) 
    ... 57 more 
Caused by: 

java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. 
    at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:95) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213) 
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191) 
    at com.google.cloud.sql.core.SslSocketFactory$ApplicationDefaultCredentialFactory.create(SslSocketFactory.java:545) 
    at com.google.cloud.sql.core.SslSocketFactory.getInstance(SslSocketFactory.java:140) 
    at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:48) 
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300) 
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251) 
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284) 
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083) 
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806) 
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:140) 
    at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:148) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) 
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410) 
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328) 
    at java.sql.DriverManager.getConnection(DriverManager.java:664) 
    at java.sql.DriverManager.getConnection(DriverManager.java:270) 
    at com.azeem.endpoint.CloudSqlServlet.doGet(CloudSqlServlet.java:70) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) 
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349) 
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) 
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) 
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) 
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) 
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) 
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:95) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:508) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at org.mortbay.jetty.Server.handle(Server.java:326) 
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) 
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) 
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547) 
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) 
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) 
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409) 
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) 
Powered by Jetty:// 

我嘗試用MySQL客戶端連接,它的做工精細,並嘗試與gcloud它也連接工作。然後我從gitHub下載示例代碼並嘗試這些代碼一切正常,然後我從樣本中複製相同的代碼,但它在現有項目中不起作用。

這是我的代碼。

CloudSqlServlet.java

package com.azeem.endpoint; 

import java.io.IOException; 
import java.io.PrintWriter; 
import java.net.Inet4Address; 
import java.net.Inet6Address; 
import java.net.InetAddress; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Timestamp; 
import java.util.Date; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

// [START example] 
@SuppressWarnings("serial") 
public class CloudSqlServlet extends HttpServlet { 

    @Override 
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, 
     ServletException { 
    String path = req.getRequestURI(); 
    if (path.startsWith("/favicon.ico")) { 
     return; // ignore the request for favicon.ico 
    } 
    // store only the first two octets of a users ip address 
    String userIp = req.getRemoteAddr(); 
    InetAddress address = InetAddress.getByName(userIp); 
    if (address instanceof Inet6Address) { 
     // nest indexOf calls to find the second occurrence of a character in a string 
     // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf() 
     userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*"; 
    } else if (address instanceof Inet4Address) { 
     userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*"; 
    } 

    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits (visit_id INT NOT NULL " 
     + "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, " 
     + "PRIMARY KEY (visit_id))"; 
    final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)"; 
    final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC " 
     + "LIMIT 10"; 

    PrintWriter out = resp.getWriter(); 
    resp.setContentType("text/plain"); 
    String url; 
    if (System 
     .getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) { 
     // Check the System properties to determine if we are running on appengine or not 
     // Google App Engine sets a few system properties that will reliably be present on a remote 
     // instance. 
     url = System.getProperty("ae-cloudsql.cloudsql-database-url"); 
     try { 
     // Load the class that provides the new "jdbc:google:mysql://" prefix. 
     Class.forName("com.mysql.jdbc.GoogleDriver"); 
     } catch (ClassNotFoundException e) { 
     throw new ServletException("Error loading Google JDBC Driver", e); 
     } 
    } else { 
     // Set the url with the local MySQL database connection url when running locally 
     url = System.getProperty("ae-cloudsql.local-database-url"); 
    } 
    log("connecting to: " + url); 
    try (Connection conn = DriverManager.getConnection(url); 
     PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) { 
     conn.createStatement().executeUpdate(createTableSql); 
     statementCreateVisit.setString(1, userIp); 
     statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime())); 
     statementCreateVisit.executeUpdate(); 

     try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) { 
     out.print("Last 10 visits:\n"); 
     while (rs.next()) { 
      String savedIp = rs.getString("user_ip"); 
      String timeStamp = rs.getString("timestamp"); 
      out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n"); 
     } 
     } 
    } catch (SQLException e) { 
     throw new ServletException("SQL error", e); 
    } 
    } 
} 

Web.xml中

<!-- Test Cloud SQL servlet --> 
    <servlet> 
    <servlet-name>cloudsql</servlet-name> 
    <servlet-class>com.azeem.endpoint.CloudSqlServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
    <servlet-name>cloudsql</servlet-name> 
    <url-pattern>/cloudsql</url-pattern> 
    </servlet-mapping> 

應用服務引擎-web.xml中

<threadsafe>true</threadsafe> 
    <sessions-enabled>false</sessions-enabled> 

    <use-google-connector-j>true</use-google-connector-j> 

    <system-properties> 
    <property name="ae-cloudsql.cloudsql-database-url" value="jdbc:google:mysql://${INSTANCE_CONNECTION_NAME}/${database}?user=${user}&amp;password=${password}" /> 
    <property name="ae-cloudsql.local-database-url" value="jdbc:mysql://google/${database}?cloudSqlInstance=${INSTANCE_CONNECTION_NAME}&amp;socketFactory=com.google.cloud.sql.mysql.SocketFactory&amp;user=${user}&amp;password=${password}&amp;useSSL=false" /> 
    </system-properties> 

的pom.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 

    <modelVersion>4.0.0</modelVersion> 
    <packaging>war</packaging> 
    <version>0.1.0-SNAPSHOT</version> 

    <groupId>com.azeem.endpoint</groupId> 
    <artifactId>EndPoint</artifactId> 

    <properties> 
    <!-- INSTANCE_CONNECTION_NAME from Cloud Console > SQL > Instance Details > Properties 
    or gcloud sql instances describe <instance> 
    project:region:instance for Cloud SQL 2nd Generation or 
    project:instance  for Cloud SQL 1st Generation 
--> 
    <INSTANCE_CONNECTION_NAME>analog-premise-181709:asia-northeast1:instancename</INSTANCE_CONNECTION_NAME> 
    <user>root</user> 
    <password>password</password> 
    <database>databasename</database> 

    <appengine.maven.plugin.version>1.3.1</appengine.maven.plugin.version> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
    <maven.compiler.source>1.7</maven.compiler.source> 
    <maven.compiler.target>1.7</maven.compiler.target> 
    <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation> 
    </properties> 

    <prerequisites> 
    <maven>3.3.9</maven> 
    </prerequisites> 

    <dependencies> 

    <!-- Driver injected at runtime by the use of <use-google-connector-j> in appengine-web.xml --> 
    <dependency> <!-- ONLY USED LOCALY --> 
     <groupId>mysql</groupId> 
     <artifactId>mysql-connector-java</artifactId> 
     <version>5.1.42</version> <!-- v5.x.x is for production, v6.x.x EAP X DevAPI --> 
    </dependency> 
    <dependency> 
     <groupId>com.google.cloud.sql</groupId> 
     <artifactId>mysql-socket-factory</artifactId> 
     <version>1.0.4</version> 
    </dependency> 

    <!-- Compile/runtime dependencies --> 
    <dependency> 
     <groupId>javax.servlet</groupId> 
     <artifactId>servlet-api</artifactId> 
     <version>2.5</version> 
     <scope>provided</scope> 
    </dependency> 
    <dependency> 
     <groupId>jstl</groupId> 
     <artifactId>jstl</artifactId> 
     <version>1.2</version> 
    </dependency> 

    <!-- Test Dependencies --> 
    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>4.12</version> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
<groupId>com.google.appengine</groupId> 
<artifactId>appengine-api-1.0-sdk</artifactId> 
<version>1.9.55</version> 
</dependency> 
<dependency> 
<groupId>com.google.endpoints</groupId> 
<artifactId>endpoints-framework</artifactId> 
<version>2.0.8</version> 
</dependency> 
</dependencies> 

    <build> 
    <!-- for hot reload of the web application--> 
    <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory> 
    <plugins> 
     <plugin> 
     <groupId>org.codehaus.mojo</groupId> 
     <artifactId>versions-maven-plugin</artifactId> 
     <version>2.3</version> 
     <executions> 
      <execution> 
      <phase>compile</phase> 
      <goals> 
       <goal>display-dependency-updates</goal> 
       <goal>display-plugin-updates</goal> 
      </goals> 
      </execution> 
     </executions> 
     </plugin> 

     <plugin> 
     <groupId>com.google.cloud.tools</groupId> 
     <artifactId>appengine-maven-plugin</artifactId> 
     <version>${appengine.maven.plugin.version}</version> 
     </plugin> 
    </plugins> 
    </build> 
</project> 

我輸入正確的實例名稱和密碼和數據庫,在這裏我只是將其刪除。

您能否讓我知道爲什麼這不起作用。我運行示例代碼時工作正常。

+0

如果你從App Engine的標準連接,您使用的是錯誤的庫。請按照此處的說明進行操作:https://cloud.google.com/appengine/docs/standard/java/cloud-sql/ – Vadim

+0

我正嘗試使用本地主機進行連接。如果我使用錯誤的lib,那麼爲什麼它在我運行示例代碼時工作?我只是從示例 –

+0

@Vadim複製這段代碼好吧,我改變了lib仍然無法正常工作。我發現一個區別,當我運行示例代碼,它需要'mvn appengine:devserver',但是當我運行我的代碼時,它需要'mvn appengine:run'是一個問題 –

回答

0

您沒有創建默認憑據,既沒有設置環境變量GOOGLE_APPLICATION_CREDENTIALS也沒有在您的代碼中調用credientials,除了您的pom.xml中沒有提到缺省憑證Google API client libraries以添加它:

<dependencies> 
    <dependency> 
    <groupId>com.google.api-client</groupId> 
    <artifactId>google-api-client</artifactId> 
    <version>1.22.0</version> 
    </dependency> 
    </dependencies> 

to start

+0

我添加這個「依賴」,但仍然無法正常工作。我已經用這個命令'gcloud auth application-default login'創建憑證 –

+0

如果你這樣做了,你現在有什麼錯誤? –

+0

沒有更改相同的錯誤 –