I am trying to write a simple web service that must take a number as input and return details corresponding to it.
Here is my code that I have written till now.
package webserviceapp;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
#WebService
public class WebServiceApp {
/**
* #param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.100.66.28:3306/dbname";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
// TODO code application logic here
Connection conn;
Statement stmt;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql = "Select * from table";
ResultSet rs;
rs = stmt.executeQuery(sql);
while(rs.next()){
//do something
}
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
#WebMethod(action = "returnDetails")
public static String[] returnDetails(int k) throws notFoundException{
//do the work
//returns String[]
}
private static class notFoundException extends Exception {
public notFoundException(String s) {
System.out.println(s);
System.err.println(s);
}
}
}
I do not know how to take input for the above web service. I have a html page that has a text box and submit button for which I get values through a php code. I want to tunnel this number as input to my web service. Can anyone tell me how can I proceed.
Also, I want the output String[] to be returned to php code so it can be displayed on the html page.
Thanks in advance.
you can pass it in the URL and from the url you can get the values in java
Working off the assumption that you are looking to invoke a RESTful service, there are multiple ways of obtaining input parameters. You can refer to the below article for the ways to achieve this -
http://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters
Code examples for each are available at http://www.java4s.com/web-services/
Another good article you can refer to is - https://vrsbrazil.wordpress.com/2013/08/07/passing-parameters-to-a-restful-web-service/
Related
I have an application with a login form. What I want is simply retrieve the credentials of the user who logs in, i.e select the username and password from the login form and make a simple select query. However the resultset always return null, no matter what changes I made. I would like to ask what could be the problem? For the purpose of testing I have made 2 static variable in which I store the retrieved username and password (I will made the other alongside these fields in 1 class User but after I fix this). Here is the code: /The fields in the database are exactly like the ones written in the brackets of the getString() method/
package graphical_interface;
import business_logic.User;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Controller {
#FXML
public Button loginB;
public Button exitB;
public TextField userinp;
public TextField passinp;
public Parent pr;
public static String s1 = null;
public static String s2 = null;
#FXML
private void closeApp() {
Platform.exit();
}
String username = null;
String password = null;
#FXML
private void checkB(){
try {
PreparedStatement pstmt2 = null;
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://remotemysql.com/CXcocPWj6l", "CXcocPWj6l", "czNrEV9umD");
String query = "select * from User where Username = ? and PassWord = ?";
pstmt2.setString(1,userinp.getText());
pstmt2.setString(2,passinp.getText());
ResultSet valueExist = pstmt2.executeQuery(query);
if(valueExist.next()){
s1 = valueExist.getString("Username");
s2 = valueExist.getString("PassWord");
// System.out.println(valueExist.getString("PassWord");
}
conn.close();
System.out.println(s1);
System.out.println(s2);
} catch (Exception exp){
System.out.println(exp.getLocalizedMessage());
}
}
}
The SQL syntax seems to be correct, so few questions: are you sure that the table contains the record you are finding for? Are you sure that "userinp.getText()" and "passinp.getText()" return something not null?
Finally two advice: use try with resource or at least use the finally block.
Replace the columnLabel with columnIndex i.e. replace
if(valueExist.next()){
s1 = valueExist.getString("Username");
s2 = valueExist.getString("PassWord");
}
with
if(valueExist!=null && valueExist.next()){
s1 = valueExist.getString(columnIndex-of-Username);
s2 = valueExist.getString(columnIndex-of-PassWord);
}
where columnIndex-of-Username and columnIndex-of-PassWord are integer values holding the columnIndex of Username and PassWord respectively.
Note: the first column is 1, the second is 2, ...
If you have any typo in columnLabels, it may help fix your problem. Using columnIndex instead of columnLabel has another advantage of performance improvement (check https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_72/rzaha/jdbcperf.htm)
I'm coding for hours to insert data into my SQL database, but nothing happens.
I even can't debug Java, because I don't get any output of my console.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author xxx
*/
public class MyServlet extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/userdata";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final DecimalFormat DF2 = new DecimalFormat("#.##");
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
String myDriver = "com.mysql.jdbc.Driver";
try {
Class.forName(myDriver);
// opening database connection to MySQL server
con = DriverManager.getConnection(URL, USER, PASSWORD);
// getting Statement object to execute query
// the mysql insert statement
String query = "INSERT INTO customers (customer, currency, amount) values ('Name', 'Currency', 100);";
stmt.executeUpdate(query);
// execute the preparedstatement
// executing SELECT query
rs = stmt.executeQuery(query);
con.close();
stmt.close();
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
What did I wrong, that nothing happens? Even if I use this code for Java-Classes (not Servlets), I only receive an compile error, but without message.
I'm using the IDE Netbeans and mysql DB is the MySQL Workbench. The Java Class is using the main method.
Update:
I've tested following Code with IntelliJ:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/userdata";
String user = "root";
String password = "root";
String query = "Insert into customers (customer, currency, amount) values('Michael Ballack', 'Euro', 500)";
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query)) {
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private static class JdbcMySQLVersion {
public JdbcMySQLVersion() {
}
}
I can insert data into the MySQL database.
In Netbeans this code won't work, although I've implemented the MySQLConnector. I don't know why, but Netbeans seems hard to handle.
In the servlet code, I don't see you ever write anything to out. So nothing is being sent back to the browser, even if it compiled. You could write your SQL exception to the out writer you created. To be more precise add this in your exception: out.println(sqlEx.printStackTrace()); That should at least show what exception you are getting back to the browser.
What is the compile error you get outside of a servlet?
This maybe obvious, but to get JDBC stuff to work on your server, you need to have the MySQL server installed, started and configured. The table referenced has to be defined, etc. You could check this outside of the Java servlet environment with the tools provided with MySQL.
your code can not compile, you miss catch exception for second 'try'.
Where do you use this class to run, if you run a java class, this class must contain main() function?
you should use some IDEs like eclipse or IntelliJ to code, it help you detect the error easier.
I found the solution. If you are using Netbeans with the Glassfish-Server and you want your servlet to save data into the database, you have to make sure that Netbeans has installed the Driver of your Database Connector (e.g. MySQL Connector). But you also have to configurate your server (e.g. Glassfish) which will support the DB Connector drivers.
In my case my Server didn't load the DB Connector Driver so the JDBC Code couldn't be executed.
Here's a useful link to configurate the Glassfish Server: https://dzone.com/articles/nb-class-glassfish-mysql-jdbc
I am new to android, So i need a basic knowledge,How to connect to the database and Select some of the values from it.
These are all the following steps i have already completed by watching and reading some online tutorials.
Created a New ANDROID Project Named And2.
Created a New JAVA Project named MYSQLConnection which is used to store the database connection.
I have Downloaded mysql-connector-java-5.1.34 file Online and added it.
I have attached the Screen Shot the total overview of my eclipse.
Now i just needed to access the database in And2 and Write a Simple Select Query So that i can make sure that connection is created.
Shown below is the Java file for DB Connection.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import com.mysql.jdbc.*;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.Statement;
public class Main {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
try
{
String connectionUrl = "jdbc:mysql://localhost:3306/testdatabase";
String connectionUser = "root";
String connectionPassword = "12345";
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
//Statement stmt = conn.createStatement();
// ResultSet reset = stmt.executeQuery("select * from TableName");
//
// //Print the data to the console
// while(reset.next()){
// Log.w("Data:",reset.getString(3));
//
// }
}
catch ( SQLException err )
{
System.out.println("Database connection failed");
}
}
}
Any Help appreciated.
I have written some code that retrieves a video from a database. This video is stored as a BLOB file. I have retrieved it in
package edu.jay.fyp.featureextractor.database;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleResultSet;
import oracle.ord.im.OrdVideo;
public class OracleConnector {
private static final String dbUrl = "jdbc:oracle:thin:#jay_tank-pc:1521:fyp";
private static final String user = "SYSTEM";
private static final String pwd = "xyz";
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
OracleConnection connection = (OracleConnection) DriverManager.getConnection(dbUrl,user,pwd);
System.out.println("Connected");
String query = "select video_name, video_content from system.videos where sr_no = '1'";
PreparedStatement ps = connection.prepareStatement(query);
OracleResultSet rs = (OracleResultSet) ps.executeQuery();
OrdVideo videoProxy = null;
if(rs.next()){
rs.getORAData("video_content", OrdVideo.getORADataFactory());
}
//System.out.println(videoProxy.getBitRate());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I used code similar to the code given in Oracle's documentation, but when I run my code, I get the following exceptions:
Exception in thread "main" java.lang.ClassCastException: oracle.sql.BLOB cannot be cast to oracle.sql.STRUCT
at oracle.ord.im.OrdVideo.create(OrdVideo.java:1797)
at oracle.ord.im.OrdVideo$1.create(OrdVideo.java:1786)
at oracle.jdbc.driver.Accessor.getORAData(Accessor.java:1387)
at oracle.jdbc.driver.OracleResultSetImpl.getORAData(OracleResultSetImpl.java:1408)
at oracle.jdbc.driver.OracleResultSet.getORAData(OracleResultSet.java:632)
at edu.jay.fyp.featureextractor.database.OracleConnector.main(OracleConnector.java:28)
Well, I don't know much about this but I've done some research.
The error, if you read it says that a blob cannot be cast to a struct. That gives you a hint that you're providing wrong arguments to the getORAData().
I went and looked at the definition, and it says:
Get the column value as an instance of a subclass of ORAData
Well, if you look at the ORAData definition it doesn't seem to support BLOB, but only more common value types.
So, clearly that is not the way to retrieve a BLOB from the DB.
Searching on how to actually do that, I found this Java: Reading Blob from Oracle
In the response you can see that he suggest using ResultSet.getBinaryStream()
So your code should probably be:
rs.getBinaryStream("video_content")
Or
rs.getBytes("video_content")
Of course now you have to pick up the InputStream or the byte[] results and do something with them, but I'll leave that for you.
package database;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import database.Dbconnect;
public class CreateQuery {
Connection conn;
/**
* #throws ClassNotFoundException
* #throws SQLException
* #throws IOException
*/
public CreateQuery() throws ClassNotFoundException, SQLException, IOException {
conn=new Dbconnect().returnDatabaseConnection();
}
public int addNewLayertoDB(String feature_name,String shape,int Latitude , int Longitude , int feature_geom , String feature_details){
try {
PreparedStatement statement = null;
String table_name = feature_name + "_" + shape;
String query = "CREATE TABLE EtherMap "+table_name+" ("+ feature_name+" (20))";
statement = conn.prepareStatement(query);
statement.setString(1, feature_name);
statement.execute();
String squery = "ALTER TABLE EtherMap" +table_name+" ADD COLUMN geom int , ADD COLUMN shape character(10)";
return 1;
} catch (SQLException ex) {
return 0;
}
}
public void closeConn() throws SQLException {
if (conn != null) {
this.conn.close();
}
}
}
I want to test this java code to see if anything is being updated in the postgresql database .
How do I do this in ecclipse IDE ?
There is nothing in this code that requires it to be in a web-app.
That's a good thing, as web-apps are components of their Servlet containers. In other words, you can't really run a standalone web-app, you must deploy it. Perhaps you'll deploy it in a micro-container that only contains your application, but there's nothing like true stand-alone running of a component.
In your case, just add a public static void main(String[] args) { to this code, put the desired calls to create the class and perform the operations, and give it a spin. If it's not just a "quick check" but a formal test that might be repeated, look into JUnit.
I would suggest writing a TestCase and making sure (assert)that the data you store in postgres, you can read it.