Display details on specific user using rest web service, queryparam - java

I am making a log in form on java. Restful web service. I have done logging in and in registration. I have here inputting plate number. I want to retrieve data based on the inputted plate number. I have here the scanning only of the plate number if it is in the database, but I dont know how to display the details of it. Here's my code. I'm so confused. I don't know how to do it.
Constants.java
package com.taxisafe.connection;
public class Constants {
public static String dbClass = "com.mysql.jdbc.Driver";
private static String dbName= "taxisafe";
public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName;
public static String dbUsername = "root";
public static String dbPassword = "";
}
DatabaseConnection.java
package com.taxisafe.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.taxisafe.objects.Objects;
public class DatabaseConnection {
#SuppressWarnings("finally")
public static Connection createConnection() throws Exception {
Connection koneksyon = null;
try {
Class.forName(Constants.dbClass);
koneksyon = DriverManager.getConnection(Constants.dbUrl, Constants.dbUsername, Constants.dbPassword);
} catch (Exception e) {
throw e;
} finally {
return koneksyon;
}
}
//CHECK FOR LOGIN
public static boolean checkUser(String username, String password) throws Exception { //checkLogin to checkUser
boolean UserRecorded = false;
Connection konek = null;
try {
try {
konek = DatabaseConnection.createConnection();
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "SELECT * FROM user WHERE username = '" + username + "' AND password=" + "'" + password + "'";
ResultSet rs = statement.executeQuery(code);
while (rs.next()) {
UserRecorded = true;
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (konek != null) {
konek.close();
}
throw e;
} finally {
if (konek != null) {
konek.close();
}
}
return UserRecorded;
}
// REGISTER USER
public static boolean registertheUser(String name, String username, String email, String password) throws SQLException, Exception { //inserUser - registertheUser
boolean insertUser = false; //insertStatus - insertUser
Connection konek = null;
try{
try{
konek = DatabaseConnection.createConnection();
}
catch (Exception e){
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "INSERT into user(name, username, emailaddress, password) values('"+name+ "',"+"'" + username + "','"+ email + "','" + password + "')";
int dbrecord = statement.executeUpdate(code);
if (dbrecord > 0){
insertUser = true;
}
} catch (SQLException sqle){
throw sqle;
} catch (Exception e){
if (konek !=null){
konek.close();
}
throw e;
} finally{
if (konek !=null){
konek.close();
}
} return insertUser;
}
//CHECK PLATE NUMBER
public static boolean checkPlate(String platenumber) throws Exception { //checkLogin to checkUser
boolean PlateRecorded = false;
Connection konek = null;
try {
try {
konek = DatabaseConnection.createConnection();
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "SELECT * FROM taxi WHERE taxi_plate_no = '" + platenumber+ "'";
ResultSet rs = statement.executeQuery(code);
while (rs.next()) {
PlateRecorded = true;
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (konek != null) {
konek.close();
}
throw e;
} finally {
if (konek != null) {
konek.close();
}
}
return PlateRecorded;
}
}
JsonConstruction.java
package com.taxisafe.json;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class JsonConstruction {
public static boolean isNotNull(String text){
return text !=null && text.trim().length() >=0 ? true : false;
}
public static String JSONResponse(String tag, boolean status){
JSONObject object = new JSONObject();
try{
object.put("tag", tag);
object.put("status", new Boolean(status));
} catch (JSONException e){
} return object.toString();
}
public static String JSONResponse(String tag, boolean status, String errorMessage){
JSONObject object = new JSONObject();
try{
object.put("tag", tag);
object.put("status", new Boolean(status));
object.put("errorMessage", errorMessage);
} catch (JSONException e){
} return object.toString();
}
}
PlateNumberCheck.java
package com.taxisafe.server;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.sun.corba.se.impl.util.Utility;
import com.taxisafe.connection.DatabaseConnection;
import com.taxisafe.json.JsonConstruction;
#Path("platecheck") //for the url
public class PlateNumberCheck {
#GET
//To get the full url : http://Ipaddress:portnumber/#path/#getPath
#Path("/magcheck")
#Produces(MediaType.APPLICATION_JSON)
//Produces is for the response of JSON.
public String magcheck(#QueryParam("platenumber") String platenumber){
String sagot = "";
if(checkInput(platenumber)){
sagot = JsonConstruction.JSONResponse("checked", true);
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String platenumber){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(platenumber)){
try{
output = DatabaseConnection.checkPlate(platenumber);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
}
Please help me on how to display the details of the plate number.

Related

MYSQL JDBC java.sql.SQLException: Operation not allowed after ResultSet closed

I have a program that queries a database using different jdbc drivers. This error is specific to the MySQL driver.
Here's the basic rundown.
I have another query runner class that uses a postgresql jdbc driver that works just fine. Note the line conn.close(); this works fine on my postgresql query runner, but for this SQL runner it comes up with the error.
I have removed the line conn.close(); and this code works fine, but over time it accumulates sleeping connections in the database. How can I fix this?
New Relic is a third party application that I am feeding data to, if you dont know what it is, don't worry it's not very relevant to this error.
MAIN CLASS
public class JavaPlugin {
public static void main(String[] args) {
try {
Runner runner = new Runner();
runner.add(new MonitorAgentFactory());
runner.setupAndRun(); // never returns
}
catch (ConfigurationException e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
}
}
MYSQL QUERY RUNNER CLASS
import com.newrelic.metrics.publish.util.Logger;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLQueryRunner {
private static final Logger logger = Logger.getLogger(MySQLQueryRunner.class);
private String connectionStr;
private String username;
private String password;
public MySQLQueryRunner(String host, long port, String database, String username, String password) {
this.connectionStr = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false";
this.username = username;
this.password = password;
}
private void logError(String message) {
logger.error(new Object[]{message});
}
private void logDebugger(String message) {
logger.debug(new Object[]{message});
}
private Connection establishConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logError("MySQL Driver could not be found");
e.printStackTrace();
return null;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionStr, username, password);
logDebugger("Connection established: " + connectionStr + " using " + username);
} catch (SQLException e) {
logError("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}
public ResultSet run(String query) {
Connection conn = establishConnection();
if (conn == null) {
logError("Connection could not be established");
return null;
}
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
conn.close();
return rs;
} catch (SQLException e) {
logError("Failed to collect data from database");
e.printStackTrace();
return null;
}
}
}
AGENT CLASS
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import com.newrelic.metrics.publish.Agent;
public class LocalAgent extends Agent {
private MySQLQueryRunner queryRunner;
private String name;
private Map<String, Object> thresholds;
private int intervalDuration;
private int intervalCount;
public LocalAgent(String name, String host, long port, String database, String username, String password, Map<String, Object> thresholds, int intervalDuration) {
super("com.mbt.local", "1.0.0");
this.name = name;
this.queryRunner = new MySQLQueryRunner(host, port, database, username, password);
// this.eventPusher = new NewRelicEvent();
this.thresholds = thresholds;
this.intervalDuration = intervalDuration;
this.intervalCount = 0;
}
/**
* Description of query
*/
private void eventTestOne() {
String query = "select count(1) as jerky from information_schema.tables;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestOne");
event.add("jerky", rs.getInt("jerky"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* blah
*/
private void eventTestTwo() {
String query = "SELECT maxlen FROM information_schema.CHARACTER_SETS;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestTwo");
event.add("beef", rs.getString("maxlen"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void pollCycle() {
if (this.intervalCount % this.intervalDuration == 0) {
eventTestOne();
eventTestTwo();
this.intervalCount = 0;
}
// Always incrementing intervalCount, keeping track of poll cycles that have passed
this.intervalCount++;
}
#Override
public String getAgentName() {
return this.name;
}
}
The problem is that you are trying to access the ResultSet after the connection is closed.
You should open and close the connection in the method that is calling run() this way the connection will be open when you access and loop through the Resultset and close it in the finally block of the calling method.
Even better would be if you can just loop through the ResultSet in the run() method and add the data to an object and return the object, this way you can close it in the finally block of the run() method.

Can not insert user into database in JSON Java Restful

I'm facing the problem about insert user in database. Im using Restful and JDBC to parse data to android, I have two classes to perform insert user following as:
Register.java
#Path("/register")
public class Register {
#GET
#Path("/doregister")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
int retCode = registerUser(name, uname, pwd);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside check registerUser method() ");
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
if(DBConnection.insertUser(name, uname, pwd)){
System.out.println("RegisterUSer if");
result = 0;
}
} catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}
catch (Exception e) {
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
DBConnect.java
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
boolean insertStatus = false;
Connection dbConn = null;
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "INSERT into ACCOUNT(name, username, password) values('"+name+ "',"+"'"
+ uname + "','" + pwd + "')";
//System.out.println(query);
int records = stmt.executeUpdate(query);
//System.out.println(records);
//When record is successfully inserted
if (records > 0) {
insertStatus = true;
}
} catch (SQLException sqle) {
//sqle.printStackTrace();
throw sqle;
} catch (Exception e) {
//e.printStackTrace();
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return insertStatus;
}
My table ACCOUNT:
When I debugged on Eclipse, I see the result return is fine, but If I use Advanced rest client tool to get data, it happened an exception:
URL Json:
http://localhost:9999/webserver/register/doregister?name=tester&username=tester#gmail.com&password=test12345
status of result response:
{
"tag": "register",
"status": false,
"error_msg": "Error occured"
}
I have found and tried a lot of ways but not found the cause
How to fix the problem and insert user into database? Thank so much !

config,properties file does not update in real time while running service via the browser

i try to implement some rest api for read mails service.
now i have a command that can stop/run the service.
after i run the service for some reason when i update my config file in the runService method into "RUNNING" i still get that the status of the service is "ONHOLD" and i dont undersatnd why. there for the do while loop terminated only after 1 iteration.
there is a delay while we working with files inside the program code?
this is my full code:
package com.javacodegeeks.snippets.enterprise;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/helloWorld")
public class HelloWorldController {
private final String layout = "ViewLayout";
private static enum Status{
RUNNING,ONHOLD,FINISHED,ERROR
}
Status status;
//setup method
#RequestMapping(value = "/setup/{username}/{password}/{host}/", method = RequestMethod.GET)
public String Setup(#PathVariable("username") String username,#PathVariable("password") String pass,#PathVariable("host") String host ,ModelMap model) throws IOException {
model.addAttribute("tag","Setup configuration");
OutputStream output = null;
File myfile = new File(username+".properties");
try{
if(!checkIfFileExists(myfile)){
myfile.createNewFile();
output = new FileOutputStream(myfile,false);
}
else{
model.addAttribute("msg","Error: Setup Failed, configuration for the user ="+" "+username+" "+"already exists!");
return layout;
}
Properties prop = new Properties();
prop.setProperty("username", username);
prop.setProperty("password", pass);
prop.setProperty("host", host);
prop.setProperty("status", status.FINISHED.toString());
prop.store(output, null);
}
catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
model.addAttribute("msg","Configuration successfully updated!");
return layout;
}
//run service method
#RequestMapping(value = "/run/{username}/{password}/", method = RequestMethod.GET)
public String runService(#PathVariable("username") String username,#PathVariable("password") String pass,ModelMap model){
model.addAttribute("tag","Running service procedure");
File myfile = new File(username+".properties");
if(!checkIfFileExists(myfile)){
model.addAttribute("msg","Error: Run Failed, configuration for the user ="+" "+username+" "+"not found!");
return layout;
}
else{
int i=0;
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(myfile);
prop.load(input);
if(!authenticatePassword(prop,pass)){
model.addAttribute("msg","Error: Run Failed, The password is inccorrect");
return layout;
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String stat = prop.getProperty("status");
if(stat.equals(status.FINISHED.toString()) || stat.equals(status.ONHOLD.toString()))
{
updateConfigfile(username+".properties","status",status.RUNNING.toString());
do{
i++;
model.addAttribute("msg","inside loop"+" "+"Counter is:"+" "+i+" "+"status is =" +prop.getProperty("status"));
}while(prop.getProperty("status").equals(status.RUNNING.toString()));
}else{
model.addAttribute("msg","Service is already running");
}
}
return layout;
}
//get status
#RequestMapping(value = "/getstatus/{username}/{password}/", method = RequestMethod.GET)
public String getServiceSatus(#PathVariable("username") String username,#PathVariable("password") String pass,ModelMap model) {
model.addAttribute("tag","Get Status");
Properties prop = loadProperties(username+".properties");
if(prop == null){
model.addAttribute("msg","Error: Status is not available: can not read properties file!");
return layout;
}
if(!authenticatePassword(prop,pass)){
model.addAttribute("msg","Error: Get status failed, password or username is inccorrect");
return layout;
}
String status = prop.getProperty("status");
model.addAttribute("msg", "Service status is:"+" "+status);
return layout;
}
//stop service
#RequestMapping(value = "/stop/{username}/{password}/", method = RequestMethod.GET)
public String stopService( #PathVariable("username") String username,#PathVariable("password") String pass,ModelMap model) {
String message = "";
Properties prop = loadProperties(username+".properties");
if(prop == null){
model.addAttribute("msg","Error: Can not stop service, properties file does not exist or username is inccorrect!");
return layout;
}
if(!authenticatePassword(prop,pass)){
model.addAttribute("msg","Error: Can not stop service, password or username is inccorrect");
return layout;
}
String stat = prop.getProperty("status");
if(stat.equals(status.RUNNING.toString()))
{
updateConfigfile(username+".properties","status",status.ONHOLD.toString());
message = "Service was stoped";
}else{
message = "service is not running status is = "+ " "+prop.getProperty("status");
}
model.addAttribute("tag","Stop Service");
model.addAttribute("msg",message);
return layout;
}
public boolean checkIfFileExists(File filename){
if(!filename.exists()){
return false;
}
return true;
}
//function that updating properties file
public void updateConfigfile(String filename ,String key,String val){
FileInputStream in = null;
Properties props = new Properties();
try {
in = new FileInputStream(filename);
props.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
props.setProperty(key, val);
props.store(out, null);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
//function that load properties file
public Properties loadProperties(String filename){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(filename);
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
return null;
}
}
return prop;
}
public boolean authenticatePassword(Properties prop,String pass){
if(!(prop.getProperty("password").equals(pass))){
return false;
}
return true;
}
}
I don't really understand your problem but, at least, I think that you have a problem inside runService method:
Note:added some comments into the code starting with '<--'
String stat = prop.getProperty("status"); <-- you read the property here
if(stat.equals(status.FINISHED.toString()) || stat.equals(status.ONHOLD.toString()))
{
updateConfigfile(username+".properties","status",status.RUNNING.toString());
do{
i++;
model.addAttribute("msg","inside loop"+" "+"Counter is:"+" "+i+" "+"status is =" +prop.getProperty("status")); <-- status contains FINISHED or ONHOLD! It is the same as using stat variable.
}while(prop.getProperty("status").equals(status.RUNNING.toString())); <--contains FINISHED or ONHOLD! so, always return false
}else{
model.addAttribute("msg","Service is already running");
}
In other words, if you change the file you need to read it again in order to have an updated properties into properties object.
Hope this helps!
I mean this referred to my last comment!
String stat = prop.getProperty("status");
if(stat.equals(status.FINISHED.toString()) || stat.equals(status.ONHOLD.toString()))
{
updateConfigfile(username+".properties","status",status.RUNNING.toString());
prop.setProperty("status",status.RUNNING.toString());
i++;
model.addAttribute("msg","inside loop"+" "+"Counter is:"+" "+i+" "+"status is =" +prop.getProperty("status"));
}else{
model.addAttribute("msg","Service is already running");
}

servlet mysql Runtime Exception [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 7 years ago.
java.sql.SQLException: Parameter index out of range (1 > number of parameters,
which is 0)
For the following code, what kind of parameter change is required to make the code run?
package com.chen.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class SqlHelper {
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
private static String url = "jdbc:mysql://localhost:3306/userdata";
private static String username1 = "root";
private static String password1 = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static Connection getConnection() {
try {
conn = DriverManager.getConnection(url, username1, password1);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void executeUpdate(String sql, String[] parameters) {
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
ps.setString(i+1 , parameters[i]);
}
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
close(rs,ps,conn);
}
}
public static ResultSet executeQuery(String sql,String[]parameters){
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
if(parameters!=null&&!parameters.equals("")){
for(int i=0;i<parameters.length;i++){
ps.setString(i+1,parameters[i]);
}
}
rs=ps.executeQuery();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
//close(rs,ps,conn);
}
return rs;
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static Connection getConn() {
return conn;
}
public static PreparedStatement getPs() {
return ps;
}
public static ResultSet getRs() {
return rs;
}
}
Below is the error stack:
//java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:904)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3797)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3779)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4600)
at com.chen.util.SqlHelper.executeQuery(SqlHelper.java:100)
at com.chen.services.UserService.checkUser(UserService.java:22)
at com.chen.controller.ControllerServlet.doGet(ControllerServlet.java:33)
at
package com.chen.services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.chen.domain.User;
import com.chen.util.SqlHelper;
public class UserService {
// 用checkUser()来判断用户是否存在
public boolean checkUser(User user) {
boolean b = false;
// 使用SqlHelper来完成查询任务
String sql = "select * from user where username=? and password=?";
String parameters[] = { user.getUsername(), user.getPassowrd() };
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
// 根据rs来判断该用户是否存在
try {
if (rs.next()) {
b = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return b;
}
public ArrayList getUserByPage(int pageNow, int pageSize) {
ArrayList<User> arr = new ArrayList<User>();
// 查询sql
//String sql = "select * from user where id>3 order by id limit 20";
String sql="select sql_calc_found_rows * from user limit 0,10";
ResultSet rs = SqlHelper.executeQuery(sql, null);
// 二次封装 把 ResultSet -->User对象-->Arraylist(集合)
try {
while (rs.next()) {
User u = new User();
try {
u.setId(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassowrd(rs.getString(3));
// 一定记住 u-->ArrayList
arr.add(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return arr;
}
public int getPageCount(int pageSize) {
String sql = "select * from user";
int rowCount = 0;
ResultSet rs = SqlHelper.executeQuery(sql, null);
try {
rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rowCount = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return (rowCount - 1) / pageSize + 1;
}
//删除用户
public boolean deleUser(String id){
boolean b=true;
String sql="delete from user where id=?";
String parameters[]={id};;
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
//用过id获取用户数据
public User getUserById(String id){
User user=new User();
String sql="select * from user where id= ?";
String parameters[]={id};
ResultSet rs=SqlHelper.executeQuery(sql, parameters);
try {
if(rs.next()){
user.setId(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setPassowrd(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return user;
}
//修改用户
public boolean updateUser(User user){
boolean b=true;
String sql="update user set username=?,password=? where id=?";
String parameters[]={user.getUsername(),user.getPassowrd(),user.getId()+""};
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
}
Replace this:
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
With:
ResultSet rs = SqlHelper.executeQuery(sql, parameters);

The Values are not being dumped into the table temperature_demo

I have written this code to remove the duplicate entries from the table and then to insert it into the other table.
The code executes but the values are not being updated into the table.
Query4 is not getting executed.
Any suggestions would be helpful.
Thank you.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class duplicate
{
public static void main(String args[])
{
Statement stat=null,stat1=null,stat2=null;
Connection con=null;
ResultSet result1,result2;
int s_id=0;
String date=null,time=null,temp=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Loaded Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/preprocessor","root","bigdata");
System.out.println("Connected to mysql");
stat=con.createStatement();
stat1=con.createStatement();
stat2=con.createStatement();
String query1="insert into temperature_demo(ddslno,ddtstation_id,ddtdate,ddttime,ddtemp,ddtype_code,ddelevation) select dslno,dtstation_id,dtdate,dttime,dtemp,dtype_code,delevation from temperature_dup where dslno=1";
String query2="select * from temperature_demo";
String query3="select * from temperature_dup";
stat1.execute(query1);
result1=stat1.executeQuery(query2);
result2=stat2.executeQuery(query3);
while(result1.next())
{
s_id=result1.getInt(2);
date=result1.getString(3);
time=result1.getString(4);
temp=result1.getString(5);
break;
}
while(result2.next())
{
int sno=result2.getInt(1);
int s1_id=result2.getInt(2);
String date1=result2.getString(3);
String time1=result2.getString(4);
String temp1=result2.getString(5);
String type_cd=result2.getString(6);
String elev=result2.getString(7);
String query4="insert into temperature_demo values(sno,s1_id,'date1','time1','temp1','type_cd','elev')";
try
{
if( (s_id==s1_id)&&(date.equals(date1))&&(time.equals(time1))&&(temp.equals(temp1)) )
;
else
{
System.out.println(sno+" "+s1_id+" "+date1);
stat1.execute(query4);
}
}
catch(Exception ex)
{
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
if(con!=null)
try
{
con.close();
}
catch(Exception ex)
{
}
if(stat1!=null)
try
{
stat1.close();
}
catch(Exception ex)
{
}
if(stat2!=null)
try
{
stat2.close();
}
catch(Exception ex)
{
}
}
}
}
I made the changes and the following code is the result.
PreparedStatement pstat;
pstat=con.prepareStatement("INSERT INTO temperature_demo VALUES(?,?,?,?,?,?,?)");
while(result2.next())
{
int sno=result2.getInt(1);
int s1_id=result2.getInt(2);
String date1=result2.getString(3);
String time1=result2.getString(4);
String temp1=result2.getString(5);
String type_cd=result2.getString(6);
String elev=result2.getString(7);
try
{
if( (s_id==s1_id)&&(date.equals(date1))&&(time.equals(time1))&&(temp.equals(temp1)) )
;
else
{
System.out.println(sno+" "+s1_id+" "+date1);
pstat.setInt(1,sno);
pstat.setInt(2,s1_id);
pstat.setString(3,date1);
pstat.setString(4,time1);
pstat.setString(5,temp1);
pstat.setString(6,type_cd);
pstat.setString(7,elev);
}
The first statement in the else block seems to execute perfectly. The following pstat statements(pstat is a preparedStatement variable) aren't executing

Categories