Json object from database in java - java

Can anyone help me how to create a JSON Object from the database?
This is what the JSON output should look like:
{“devicelist”:{
“device”: [
{“id”: “01”, “type”: “CAM”, “name”: “Livingroom”}
{“id”: “15”, “type”: “CAM”, “name”: “Kitchen”}
]
}}
This is my code:
if (reg!=null)
{
try
{
con = ds.getConnection();
Statement select = con.createStatement();
ResultSet result=select.executeQuery("Select type,name,demo from register_device");
while (result.next())
{
String type_json=result.getString("type");
String name_json=result.getString("name");
String id_json=result.getString("demo");
JSONArray arrayObj=new JSONArray();
}
}
catch(Exception e)
{
}
}
I am able to get the selected type,name,demo from the database.
I don't know how to start the JSON coding.

If you want to extract the data from the DB and construct the JSON Object yourself, you can do:
JsonArray jArray = new JsonArray();
while (result.next())
{
String type_json=result.getString("type");
String name_json=result.getString("name");
String id_json=result.getString("demo");
JsonObject jObj = new JsonObject();
jobj.put("id", id_json);
jobj.put("type", type_json);
jobj.put("name", name_json);
jArray.put(jObj);
}
JsonObject jObjDevice = new JsonObject();
jObjDevice.put("device", jArray);
JsonObject jObjDeviceList = new JsonObject();
jObjDevice.put("devicelist", jObjDevice );
now jObjDeviceList contains all the data.

If you have a Device objects, json-lib can serialize the object using get() methods as JSON.
import java.util.*;
import net.sf.json.*;
public class JsonEncode {
public static void main(String[] args) throws Exception {
Device d1 = new Device("01", "CAM", "LivingRoom");
Device d2 = new Device("15", "CAM", "Kitchen");
List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2));
JSONArray serializedDevices = JSONArray.fromObject(devices);
JSONObject jsonDevices = new JSONObject();
jsonDevices.put("devices", serializedDevices);
JSONObject json = new JSONObject();
json.put("deviceList", jsonDevices);
System.out.println(json);
}
public static class Device {
Device(String id, String type, String name) {
this.id = id;
this.type = type;
this.name = name;
}
private String id;
public String getId() { return id; }
private String type;
public String getType() { return type; }
private String name;
public String getName() { return name; }
}
}
Saved as: JsonEncode.java
Compiled with:
javac -cp json-lib-2.4-jdk15.jar JsonEncode.java
Executed with (Note: classpath has DOS separator):
java -cp .;json-lib-2.4-jdk15.jar;commons-lang-2.6.jar;commons-logging-1.1.1.jar;commons-collections-3.2.1.jar;ezmorph-1.0.6.jar;commons-beanutils-1.8.0.jar JsonEncode
Dependencies:
json-lib-2.4-jdk15.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
commons-collections-3.2.1.jar
commons-beanutils-1.8.0.jar
ezmorph-1.0.6.jar

With jOOQ, you could produce a similar JSON list from your database:
String json = create.select(TYPE, NAME, DEMO)
.from(REGISTER_DEVICE)
.fetch()
.formatJSON();
The JSON String would look like this (configurable):
{fields:["TYPE","NAME","DEMO"],
records:[["01","CAM","Livingroom"],["15","CAM","Kitchen"]]}
See more here. Alternatively, you can use your RDBMS's native SQL/JSON capabilities to create arbitrarily nested JSON documents.
(Disclaimer: I work for the company behind jOOQ)

package com.idal.cib;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
static Connection conn1 = null;
public static Connection getDbConnection(String driver, String url,
String username, String password) {
// TODO Auto-generated constructor stub
try {
Class.forName(driver);
conn1 = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn1;
}
}
package com.idal.cib;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class DBJsonConverter {
static ArrayList<String> data = new ArrayList<String>();
static Connection conn = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
static String path = "";
static String driver="";
static String url="";
static String username="";
static String password="";
static String query="";
#SuppressWarnings({ "unchecked" })
public static void dataLoad(String path) {
JSONObject obj1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
conn = DatabaseConnector.getDbConnection(driver, url, username,
password);
try {
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
ArrayList<String> columnNames = new ArrayList<String>();
if (rs != null) {
ResultSetMetaData columns = rs.getMetaData();
int i = 0;
while (i < columns.getColumnCount()) {
i++;
columnNames.add(columns.getColumnName(i));
}
while (rs.next()) {
JSONObject obj = new JSONObject();
for (i = 0; i < columnNames.size(); i++) {
data.add(rs.getString(columnNames.get(i)));
{
for (int j = 0; j < data.size(); j++) {
if (data.get(j) != null) {
obj.put(columnNames.get(i), data.get(j));
}else {
obj.put(columnNames.get(i), "");
}
}
}
}
jsonArray.add(obj);
obj1.put("header", jsonArray);
FileWriter file = new FileWriter(path);
file.write(obj1.toJSONString());
file.flush();
file.close();
}
ps.close();
} else {
JSONObject obj2 = new JSONObject();
obj2.put(null, null);
jsonArray.add(obj2);
obj1.put("header", jsonArray);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
rs.close();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#SuppressWarnings("static-access")
public static void main(String[] args) {
// TODO Auto-generated method stub
driver = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:#10.11.34.134:1521:COREMUAT";
username = "oasisusr";
password = "p#g_ay0w";
path = "D:\\VF_Polaris\\968670\\category_list1.json";
query = "select * from temp_employee";
DatabaseConnector dc = new DatabaseConnector();
dc.getDbConnection(driver,url,username,password);
DBJsonConverter formatter = new DBJsonConverter();
formatter.dataLoad(path);
}
}

Related

How to return a value in nested try catch and while loop in java

I am using the below piece of code to SSH to a remote machine and get api_key.
I have used a try-catch block and if and while loop to return the API key value.
Below are the steps -
SSH to Remote machine
run cat command
cat command returns JSON array like below -
[
{
"apikey": "ewr34234gfdg435",
"app": "app1",
"role": "superadmin",
"user": "req1"
},
{
"apikey": "23rsgsfg3434",
"app": "app1",
"role": "superadmin",
"user": "req2"
}
]
Now, I want to retrieve the API key which has user="req2" only.
Below is the code -
package app1;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.jcraft.jsch.JSchException;
import com.pastdev.jsch.DefaultSessionFactory;
import com.pastdev.jsch.command.CommandRunner;
public class GetAPIKeyValue {
public String getAPIKeyValue(String remote_machine_user,String remote_machine_host, String remote_machine_password) {
String api_key_value = null;
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(remote_machine_user, remote_machine_host, 22);
System.out.println("Connecting to Host : " + remote_machine_host + " As user : " + remote_machine_user);
Map<String, String> props = new HashMap<String, String>();
props.put("StrictHostKeyChecking", "no");
sessionFactory.setConfig(props);
System.out.println("Entering Password on Remote Machine to connect");
sessionFactory.setPassword(remote_machine_password);
CommandRunner runner = new CommandRunner(sessionFactory);
System.out.println("Executing cat command to get apikey on host");
String command = "cat /etc/usr/apikey.sh";
CommandRunner.ExecuteResult result;
try {
result = runner.execute(command);
if (result.getStderr().isEmpty()) {
System.out.println(result.getStdout());
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(result.getStdout());
JSONArray arrayObj = (JSONArray) obj;
Iterator<JSONObject> iterator = arrayObj.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
api_key_value = (String) jsonObj.get("apikey");
String requestor = (String) jsonObj.get("user");
// Would like to condition here i.e if user=="req2" return the API key of user req2.
}
} else {
System.out.println(result.getStderr());
}
} catch (JSchException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
try {
runner.close();
} catch (IOException e) {
e.printStackTrace();
}
return api_key_value;
}
}
Currently i am returning at the end of try catch "return api_key_value;". Instead how can i return in while statement itself
Maybe use Thread can help.
if(user =="req2") {
String finalApi_key_value = api_key_value;
new Thread(new Runnable() {
#Override
public void run() {
sendApiKeyValue(finalApi_key_value);
}
}).start();
}
And creat a method called sendApiKeyValue:
private void sendApiKeyValue(String finalApi_key_value) {
// Do something.
}
I fixed the issue myself.
while (iterator.hasNext()) {
JSONObject jsonObj = iterator.next();
String user = (String) jsonObj.get("user");
if (user.equals("req2")) {
System.out.println("Got User's API Key");
api_key_value = (String) jsonObj.get("apikey");
break;
} else {
System.out.println("Searching user's API Key");
}
}
Be simple. Just refactor your code first.
public class GetAPIKeyValue {
public static String getApiKeyValue(String remoteMachineUser, String remoteMachineHost, String remoteMachinePassword) throws Exception {
DefaultSessionFactory sessionFactory = new DefaultSessionFactory(remoteMachineUser, remoteMachineHost, 22);
sessionFactory.setConfig(Map.of("StrictHostKeyChecking", "no"));
sessionFactory.setPassword(remoteMachinePassword);
return executeAndGetApiKeyForUser(sessionFactory, "req2");
}
private static String executeAndGetApiKeyForUser(SessionFactory sessionFactory, String user) throws Exception {
try (CommandRunner runner = new CommandRunner(sessionFactory)) {
System.out.println("Executing cat command to get apikey on host");
String command = "cat /etc/usr/apikey.sh";
CommandRunner.ExecuteResult result = runner.execute(command);
if (result.getStderr().isEmpty())
return getApiKeyForUser(result.getStdout(), user);
System.out.println(result.getStderr());
return null;
}
}
private static String getApiKeyForUser(String json, String user) throws ParseException {
JSONArray arrayObj = (JSONArray)new JSONParser().parse(json);
Iterator<JSONObject> it = (Iterator<JSONObject>)arrayObj.iterator();
while (it.hasNext()) {
JSONObject obj = it.next();
if (obj.get("user").equals(user))
return String.valueOf(obj.get("apikey"));
}
return null;
}
}

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.

How can I use spring on the following class?

I am learning how to use sprint and to be honest I think it's useful when you know what to inject. I am having a dilemma on the following class:
package Edamam;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
#Component
public class EdamamApi {
private String ApplicationIDRecipes;
private String ApplicationKeyRecipes;
private String ApplicationIDIngredients;
private String ApplicationKeyIngredients;
public EdamamApi(){
Properties prop = new Properties();
InputStream input = null;
try{
input = new FileInputStream("src/main/java/Edamam/Edamam.properties");
prop.load(input);
this.ApplicationIDRecipes = prop.getProperty("Application_ID_Recipes");
this.ApplicationKeyRecipes = prop.getProperty("Application_Keys_Recipes");
this.ApplicationIDIngredients = prop.getProperty("Application_ID_Ingredients");
this.ApplicationKeyIngredients = prop.getProperty("Application_Keys_Ingredients");
}
catch(IOException ex){
ex.printStackTrace();
}finally{
if(input != null){
try{
input.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
private String makeUrlForRecipes(ArrayList<String> ingredients){
boolean isFirst = true;
String url = "https://api.edamam.com/search?q=";
for(String ingredient : ingredients){
if(!isFirst)
url = url + "%20";
isFirst = false;
url = url + ingredient;
}
url = url + "&app_id=" + this.ApplicationIDRecipes + "&app_key=" + this.ApplicationKeyRecipes;
return url;
}
private String makeUrlForIngredients(String ingredient){
String url = "https://api.edamam.com/api/nutrition-data?app_id="+this.ApplicationIDIngredients+
"&app_key="+this.ApplicationKeyIngredients+"&ingr=1%20large%20"+ingredient;
return url;
}
private ArrayList<String> toArrayList(JSONArray arr){
ArrayList<String> StringList = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++)
StringList.add(arr.getString(i));
return StringList;
}
public ArrayList<RecipePojo> getRecipes(ArrayList<String> ingredients){
String url = makeUrlForRecipes(ingredients);
ArrayList<RecipePojo> recipes = new ArrayList<RecipePojo>();
try {
JSONObject response = JsonReader.readJsonFromUrl(url);
JSONArray jsonArray = response.getJSONArray("hits");
int NumberOfRecipes = 20;
int jsonIndex = 0;
while(jsonIndex < jsonArray.length() && NumberOfRecipes > 0){
JSONObject objectInArray = jsonArray.getJSONObject(jsonIndex);
String recipe = objectInArray.getJSONObject("recipe").getString("label");
String ImgURL = objectInArray.getJSONObject("recipe").getString("image");
ArrayList<String> IngredientLines = toArrayList(objectInArray.getJSONObject("recipe").
getJSONArray("ingredientLines"));
RecipePojo newRecipe = new RecipePojo(recipe, ImgURL, IngredientLines);
recipes.add(newRecipe);
jsonIndex++;
NumberOfRecipes--;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return recipes;
}
public NutritionFactsIngredient getNutritionFacts(String ingredient){
String url = makeUrlForIngredients(ingredient);
System.out.println("the url is: " + url);
NutritionFactsIngredient facts = null;
try{
JSONObject response = JsonReader.readJsonFromUrl(url);
int Calories = response.getInt("calories");
int TotalWeight = response.getInt("totalWeight");
JSONArray DietLabelsJson = response.getJSONArray("dietLabels");
JSONArray HealthLabelsJson = response.getJSONArray("healthLabels");
JSONArray CautionsJson = response.getJSONArray("cautions");
ArrayList<String> DietLabels = this.toArrayList(DietLabelsJson);
ArrayList<String> HealthLabels = this.toArrayList(HealthLabelsJson);
ArrayList<String> Cautions = this.toArrayList(CautionsJson);
facts = new NutritionFactsIngredient(Calories,TotalWeight,
DietLabels,HealthLabels,Cautions, ingredient);
}catch (JSONException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return facts;
}
}
I don't know if we should let spring handle the life-cycle of every object in our application. I just added the #component annotation on my class to get a taste of Spring, but I think that it's not enough. I am still instantiating objects with the new keyword inside of my methods. Should I make the classes RecipePojo and NutritionFactsIngredients components?. This is so confusing because the instances of these classes are not unique. They depend on user input. How can I use Spring on this class?
Edit: So people are telling me that instead of doing this:
#Component
public class EdamamApi{
public EdmamApi(){}
public Recipe getRecipe(String recipe ){
Recipe rep = Recipe(recipe);
return rep;
}
}
I should do this
#Component
public class EdamamApi{
public EdmamApi(){}
public void makeRecipe(String recipe, Recipe rep){
rep.setRecipeName(recipe);
}
}
In that way, the class is not tied down to Recipe and I can just use a bean Recipe.
--->THIS IS NOT RIGHT BUT IT'S WHAT I AM TRYING TO ACCOMPLISH <------
#Component
public class EdamamApi{
public EdmamApi(){}
public Recipe getRecipe(String name){
#Autowired
Recipe rep;
rep.setName(name);
return rep;
}
}

Display details on specific user using rest web service, queryparam

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.

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);

Categories