Android Studio中未处理的异常Class.forname("com.google.cloud.sql.jdbc.Driver") [英] Unhandled exception Class.forname("com.google.cloud.sql.jdbc.Driver") in Android Studio
问题描述
我在Android Studio中有一个项目,该项目具有 Google Cloud Endpoints 模块.我正在尝试将端点模块连接到同一项目中的 Google Cloud SQL 实例.
I have a project in Android Studio that has a Google Cloud Endpoints module. I'm trying to connect my endpoints module to an instance of Google Cloud SQL that I have in that same project.
在IDE中,我看到以下错误:
In the IDE I see the following error:
Unhandled exception: java.lang.ClassNotFoundException
我的gradle版本显示:
My gradle build shows:
Error:(82, 26) error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
Error:(87, 26) error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
我已启用appengine-web.xml
我不确定将SQL数据库连接到Google App Engine所需做什么.似乎比我想的要复杂.
I'm not sure what I need to do to connect to my SQL db to my Google App Engine. It seems to be more complicated than I thought.
我的代码:
@ApiMethod(name = "getLesson")
public Lesson getLesson(@Named("id") Long id) {
Lesson l = new Lesson();
l.setLessonId(345);
l.setLessonColour("Blue");
l.setLessonImage("itshappening.gif");
String url = null;
if (SystemProperty.environment.value() ==
SystemProperty.Environment.Value.Production) {
// Connecting from App Engine.
// Load the class that provides the "jdbc:google:mysql://"
// prefix.
Class.forName("com.google.cloud.sql.jdbc.Driver");
url =
"jdbc:google:mysql://app:instance?user=root";
} else {
// Connecting from an external network.
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://000.000.000.000:3306?user=root";
}
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
l.setLessonDescription(e.getStackTrace().toString());
}
try {
ResultSet rs = conn.createStatement().executeQuery(
"SELECT 1 + 56");
} catch (SQLException e) {
e.printStackTrace();
}
logger.info("Calling getLesson method");
return l;
}
任何帮助,评论或指导将不胜感激.
Any help, comments or guidance would be appreciated.
推荐答案
方法 ClassNotFoundException
当找不到给定的类时.
The method Class.forName()
will throw a ClassNotFoundException
when the given class cannot be located.
由于ClassNotFoundException
是已检查的异常,因此您实际上必须处理可能发生的可能性.您可以通过将其传递给调用方法来执行此操作.为此,您必须将其添加到方法的签名中:
Since ClassNotFoundException
is a checked exception, you actually have to deal with the possibility that one might occur. You can do this either by passing it on to the calling method. To do this, you have to add it to your method's signature:
@ApiMethod(name = "getLesson")
public Lesson getLesson(@Named("id") Long id) throws ClassNotFoundException {
// ...
然后调用当前方法的方法必须处理它.
Then the method that called the current method has to deal with it.