Retrieve data from database with Web Service
I have a problem and i am new to this. I know how to create web methods to insert and delet from database but i don't know how to get something from the database. I gues开发者_运维技巧s i have to pass the result of the query to a string and then return this string in order to get what i want. I have the following incomplete code.
@WebMethod(operationName = "getSomethingByID")
public String getSomethingByID(@WebParam(name = "idRocks")
String idRocks) {
Dal dal = new Dal();
ResultSet rs = dal.executeQuery("SELECT rocks FROM something WHERE idRocks ='" + idRocks+ "'");
try
{
if(rs.next())
{
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
How can i retrieve this information from database?
thanks
you will need something like:
String query = "SELECT rocks FROM something WHERE idSomething='" + idSomething+ "'";
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306";
Connection conn = DriverManager.getConnection(url, "root", "root");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery(query);
String result = "";
while (rs.next()) {
//'col1' refers to the value in each row in a column called col1 in you table
result += rs.getString("col1");
}
This just concatinates the values into one long string and you can then return that value.
You will need to import a JDBC Jar if you are using this approach (assuming it is a MySQL db you are using.)
精彩评论