Пожалуйста, прости меня за недостаток информации, я задаю этот вопрос другу, который не очень хорошо говорит по-английски.Я постараюсь описать проблему как можно точнее.
В следующем коде нам не удается установить соединение между сервером Tomcat и БД через диспетчер соединений, чтобы выполнить запрос INSERTION вDB.Приложение для Android отправляет данные для вставки через XFORM.Код заканчивается в диспетчере соединений, и мы не понимаем, почему он не работает.
//import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
//import java.beans.Statement;
import java.io.File;
import java.io.FileWriter;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.Date;
import java.util.Random;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
public class DemoServlet extends HttpServlet {
final static Logger logger = Logger.getLogger(DemoServlet.class);
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//boolean result=true;
JSONObject jsonobj = new JSONObject();
String query;
boolean st;
LocalDate localDate;
//out.println("<script> alert('before try');</script>");
try (PrintWriter out = response.getWriter()) {
System.out.println("its a testing file" + out);
//out.println("<script> alert('try');</script>");
//getting values from request and storing it in variables to use it further
String name = request.getParameter("Name");
String id = request.getParameter("ID");
String address = request.getParameter("Address");
String lati = request.getParameter("Latitude");
String lng = request.getParameter("Longitude");
String descrip = request.getParameter("Description");
//creating JSON
jsonobj.put("id", id);
jsonobj.put("name", name);
jsonobj.put("address", address);
jsonobj.put("latitude", lati);
jsonobj.put("longitude", lng);
jsonobj.put("description", descrip);
String output = jsonobj.toString();
// out.println("<script> alert(" + output + ")</script>");
String home = System.getProperty("user.home");
//System.out.println(home);
//File fil = new File(""+home+"/kamran.txt");
System.out.println(jsonobj);
// Connect to database
String hostName = "powerbipkserver.database.windows.net"; // update me
String dbName = "CustomerDataViewsDB"; // update me
String user = "powerbi"; // update me
String password = "ad@123min"; // update mee
String url = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;"
+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
// String uri = "jdbc:microsoft:sqlserver://powerbipkserver.database.windows.net:1433;database=CustomerDataViewsDB;user=powerbi@powerbipkserver;password=ad@123min;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
try {
// Date date= new Date();
//SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
//Date dateInString = date;
//date = sdf.parse(date);
//DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh.mm.ss");
localDate = LocalDate.now();
//System.out.println(dtf.format(localDate)); //2016/11/16
//String str="{\"address\":\"G67jh\",\"latitude\":\"89.08\",\"name\":\"kamran ali khan name\",\"description\":\"khjcva\",\"id\":\"7809\",\"longitude\":\"34.2\"}";
//Number id=78998;
Random rand = new Random();
// Obtain a number between [0 - 49].
int ide = rand.nextInt(500);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
id += 1;
System.out.println("data parse example:" + localDate);
//System.out.println("data parse example:"+dtf.format(localDate));
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
//FileHandler fh = new FileHandler("" + home + "/Adil-sir.txt");
//adding handler class ro write
try (FileWriter file = new FileWriter("" + home + "/sadia.txt")) {
file.write(output);
//append logger
// logger.addAppender(file );
// logger.addAppender(null);
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + output);
//out.println("<script> alert(" + home + ")</script>");
}
//logger.addAppender(dir);
//logger.setLevel(Level.ALL);
Connection connection = DriverManager.getConnection(url);
//Logger.getLogger(DemoServlet.class.getName()).log(Level.SEVERE, null, connection);
// final static void Logger logger = Logger.getLogger(yourclassname.class);
String schema = connection.getSchema();
// System.out.println("Successful connection - Schema: " + schema);
System.out.println("Query data example:");
System.out.println("=========================================");
String selectSql = "INSERT INTO Customers( customerid,customerdata , datecreated ) VALUES('" + ide + "','" + output + "','" + localDate + "');";
System.out.println("Query is ::" + selectSql);
//out.println("<script> alert(after connection);</script>");
Statement statement = connection.createStatement();
// String home = System.getProperty("user.home");
// System.out.println(home);
//File fil = new File(""+home+"/ali.txt");
// out.println("<script> alert(before stmt);</script>");
out.println("<script> alert(" + (statement.executeQuery(selectSql)) + ");</script>");
//statement.executeUpdate(selectSql);
//stmt.execute(query);
// System.out.println("stmt"+statement.executeUpdate(selectSql));
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "execute query result");
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
Logger.getLogger(DemoServlet.class.getName());
}
}
//return true;
//method 2
//request.getRequestDispatcher("insert.java").forward(request, response);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DemoServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Servlet Output String at " + jsonobj + "</p>");
out.println("</body>");
out.println("</html>");
//conn.close();
} // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Любая помощь будет признательна