java如何从restful web服务中获取一些数据,并将其保存到数据库中?
我已经编写了一些代码,利用SOAPUI作为用户界面,通过RESTfulWeb服务将一些数据保存到数据库中。我用@put来做这个。以下是运行的步骤:
1-在Tomcat 9.0服务器上运行代码。 2-使用SOAPUI中的URL放置一些数据
但当我在SOAPUI中使用PUT时,给出first和last的字符串值并运行它,这些值不会添加到我的数据库中。Hoewer,json文件得到了正确的值
{
"first": "Jon",
"last": "Snow"
}
以下是我的代码的重要部分:
package tomcat.rest.eclipse.database;
public class Score {
public static String first, last;
}
public class ScoreService {
@PUT
@Path("/score")
@Produces("application/json")
public String update(@QueryParam("first") String first,
@QueryParam("last") String last) {
Score.first = first;
Score.last = last;
final String var1 = Score.first;
final String var2 = Score.last;
database.insert(var1, var2);
String pattern = "{ \"first\":\"%s\", \"last\":\"%s\"}";
return String.format(pattern, Score.first, Score.last);
}
}
这是我的连接:
public class database {
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "00000";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected");
return conn;
} catch(Exception e) {System.out.println(e);}
return null;
}
public static void insert(final String var1, final String var2) {
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO student (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch(Exception e) {System.out.println(e);}
finally {
System.out.println("Insert completed");
}
}
}
控制台上的输出为:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver java.lang.NullPointerException Insert completed
如何将web服务正确连接到数据库以在数据库中保存一些记录?非常感谢你帮助我
# 1 楼答案
只需下载mysql connectorjar并将其添加到项目构建路径中
或
或者使用maven时使用jdbc mysql maven依赖项: