I don't know if I need more coffee, or my head is tired, but, I feel like an idiot :)
what am I doing wrong???
I want to call the methods within the class but I get complile errors.
Compilation failure: Compilation failure:
java:[35,1] error: illegal start of type
java:[35,21] error: <identifier> expected
java:[35,22] error: ';' expected
I can't execute this block in the class
//this is what doesn't work
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
} else {
this.loadRefDb(custkey);
}
}
my class
package com.ge.digital.fleet.dataservice.impl.processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
import com.ge.digital.fleet.dataservice.impl.db.RefDatabase;
public class RefReplicatedDataProcessor {
private static final Logger log = LoggerFactory.getLogger(RefReplicatedDataProcessor.class);
private RefDatabase refDb = null;
private DataSource dataSource;
private String custkey;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setCustkey(String custkey) {
this.custkey = custkey;
}
public void setRefDatabase(RefDatabase refDb) {
this.refDb = refDb;
}
//this is what doesn't work
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
} else {
this.loadRefDb(custkey);
}
}
public void loadRefDb(String custkey) throws SQLException {
log.info("Reference Replicated Data Processor :: start");
refDb.dropDb();
setAssociations(custkey);
refDb.replicationComplete();
log.info("Reference Replicated Data Processor :: Finish");
}
/***
* name: setAssociations(custkey)
* Loads/Builds the cache database with values found in mysql database
*
* returns a List of associations
* G1.DWATT,112-A-001_Gas_Turbine
* G1.ATID,112-A-001_Gas_Turbine
* G1.dvar, 112-A-001_Gas_Turbine
* ...
*/
public void setAssociations(String custkey) throws SQLException {
String reference = "";
String asset = "";
String dbname = "iprcmt1.fleet_associations"; //from old impl database - TODO new database impl
String query = "select reference, asset from " + dbname + " where custkey = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, custkey);
try (ResultSet rs = stmt.executeQuery()) {
if (! rs.next() ) {
log.info("SQL Warning ! No associations for key: " + custkey);
} else {
do {
reference = rs.getString(1);
asset = rs.getString(2);
log.info("SQL Associations reference: " + reference + " and asset: " + asset);
refDb.addRow(reference, asset);
} while (rs.next());
}
} catch (Exception ex) {
log.error("SQL Cannot Execute ResultSet Query!");
log.error(ex.getMessage());
}
} catch (Exception e) {
log.error("SQL Cannot Create DataSource Connection! Cannot Create Prepared Statement!");
log.error(e.getMessage());
}
}
}
maybe this ? :)
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
}
}else {
this.loadRefDb(custkey);
}
Your code is simply out of place. The code at "//this is what doesn't work" needs to be inside a method or constructor.
public RefReplicatedDataProcessor(){
//this is what didn't work
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
}
} else {
this.loadRefDb(custkey);
}
}
Perhaps you should run the split within a method
public void filter(){
if (custkey.contains(",")) {
String[] ck = custkey.split(",");
for ( String k : ck) {
this.loadRefDb(k);
} else {
this.loadRefDb(custkey);
}
}
}
Related
I created a database using DB Browser for SQLite. Now I am trying to run queries to retrieve data from the database, and I have run into an issue. When I run the query in DB Browser, the query runs smoothly. When I attempt to run the same query in Java, I get an error message. I triple-checked the query string. I looked to make sure I was not using SQLite keywords incorrectly. Why am I getting an error when I run this query Java?
SELECT
subject.id, main.name, main.link, subject.name, main_subject.weight
FROM
main_subject
LEFT JOIN
main ON main_subject.mainId = main.id
LEFT JOIN
subject ON main_subject.subjectId = subject.id
The query running correctly in DB Browser.
MCVE:
Main
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author sedrick
*/
public class Main
{
public static void main(String[] args)
{
try (DatabaseHandler databaseHandler = new DatabaseHandler()) {
List<BySubjectItemTwo> bySubjectItemTwos = databaseHandler.getBySubjectItems();
bySubjectItemTwos.forEach(System.out::println);
//databaseHandler.getByTitleItems().forEach(System.out::println);
}
catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
DatabaseHandler
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 java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author sedrick
*/
public class DatabaseHandler implements AutoCloseable
{
String dbString = "jdbc:sqlite:qDatabase.sqlite3";
private Connection conn;
public DatabaseHandler()
{
try {
conn = DriverManager.getConnection(dbString);
System.out.println("Connected to qDatabase!");
}
catch (SQLException ex) {
Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void close() throws Exception
{
conn.close();
}
public List<BySubjectItemTwo> getBySubjectItems()
{
List<BySubjectItemTwo> returnList = new ArrayList();
String sqlString = "SELECT subject.id, main.name, main.link, subject.name, main_subject.weight FROM main_subject LEFT JOIN main ON main_subject.mainId = main.id LEFT JOIN subject ON main_subject.subjectId = subject.id";
try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlString)) {
while (rs.next()) {
System.out.println(rs.getInt("subject.id") + " - " + rs.getString("main.name") + " - " + rs.getString("main.link") + " - " + rs.getString("subject.name") + " - " + rs.getInt("main_subject.weight"));
//returnList.add(new BySubjectItemTwo(rs.getInt("subject.id"), rs.getString("main.name"), rs.getString("main.link"), rs.getString("subject.name"), rs.getInt("main_subject.weight")));
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
return returnList;
}
}
BySubjectItemTwo
/**
*
* #author sedrick
*/
public class BySubjectItemTwo
{
private int subjectId;
private String mainName;
private String mainLink;
private String subjectName;
private int mainSubjectWeight;
public BySubjectItemTwo(int subjectId, String mainName, String mainLink, String subjectName, int mainSubjectWeight)
{
this.subjectId = subjectId;
this.mainName = mainName;
this.mainLink = mainLink;
this.subjectName = subjectName;
this.mainSubjectWeight = mainSubjectWeight;
}
public int getSubjectWeight()
{
return mainSubjectWeight;
}
public void setSubjectWeight(int mainSubjectWeight)
{
this.mainSubjectWeight = mainSubjectWeight;
}
public int getSubjectId()
{
return subjectId;
}
public void setSubjectId(int subjectId)
{
this.subjectId = subjectId;
}
public String getMainName()
{
return mainName;
}
public void setMainName(String mainName)
{
this.mainName = mainName;
}
public String getMainLink()
{
return mainLink;
}
public void setMainLink(String mainLink)
{
this.mainLink = mainLink;
}
public String getSubjectName()
{
return subjectName;
}
public void setSubjectName(String subjectName)
{
this.subjectName = subjectName;
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("BySubjectItemTwo{subjectId=").append(subjectId);
sb.append(", mainName=").append(mainName);
sb.append(", mainLink=").append(mainLink);
sb.append(", subjectName=").append(subjectName);
sb.append(", subjectWeight=").append(mainSubjectWeight);
sb.append('}');
return sb.toString();
}
}
Error
----------< sed.work:CreateDatabaseByTitleAndSubjectDatabase >----------
Building CreateDatabaseByTitleAndSubjectDatabase 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- exec-maven-plugin:1.5.0:exec (default-cli) # CreateDatabaseByTitleAndSubjectDatabase ---
Connected to qDatabase!
[SQLITE_ERROR] SQL error or missing database (ambiguous column name: subject.id)
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.484 s
Finished at: 2020-10-16T12:42:35-05:00
------------------------------------------------------------------------
Netbean's Info
Product Version: Apache NetBeans IDE 12.1
Java: 15; Java HotSpot(TM) 64-Bit Server VM 15+36-1562
Runtime: Java(TM) SE Runtime Environment 15+36-1562
System: Windows 10 version 10.0 running on amd64; Cp1252; en_US (nb)
Maven Project
This:
FROM main_subject, main, subject
is the problem with your query.
Remove , main, subject from your statement.
The tables main and subject are correctly joined after the LEFT joins.
When you use them also in the FROM clause this creates additional references and CROSS joins to the same tables.
Also, although SQLite allows a query to return more than 1 columns with the same name, it is a good practice to alias columns so that in the resultset all column names are different.
So give aliases to main.name and subject.name, something like this:
SELECT subject.id, main.name AS main_name, ..., subject.name AS subject_name, ...
and when you retrieve the column values don't use the table prefixes:
System.out.println(rs.getInt("id") + " - " + rs.getString("main_name") + " - " + rs.getString("link") + " - " + rs.getString("subject_name") + " - " + rs.getInt("weight"));
I've recently starting working on a java webapp (JSP / Servlet) that was developed by the internal developer of a company.
This app randomly doesn't return data, and inspecting the log I found some NullPointerExceptions related to the classes' member variable which holds the database connection. Following the stack trace it seems that a second thread closes the connection after it ended its task leaving the first thread without a connection.
By the needs of the company the app uses different databases, one which rules appdata, and others which contain data the app has to retrieve. So every class attached to the main servlet may connect to one or more databases depending on the task it has to accomplish.
I'm not familiar with JavaEE but giving a look at the database connection class, I see nothing which protect threads from conflicting each other.
Which is the correct way to handle such connections?
This is the code of the Database handler:
package it.metmi.mmasgis.utils;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class DBManager
{
private String szDatabase;
private String szUsername;
private String szPassword;
private String szError;
private Connection db;
private boolean bConnected;
private Logger logger;
public DBManager(String szDBName)
{
this(szDBName, "", "");
}
public DBManager(String szDBName, String szName, String szPass)
{
szDatabase = szDBName;
szUsername = szName;
szPassword = szPass;
bConnected = false;
szError = "";
logger = LogManager.getFormatterLogger(DBManager.class.getName());
}
public boolean connect()
{
logger.entry();
try {
Class.forName("com.mysql.jdbc.Driver");
if(!szDatabase.isEmpty())
{
String szCon = "jdbc:mysql://localhost/" + szDatabase;
if(!szUsername.isEmpty())
{
szCon += "?user=" + szUsername;
if(!szPassword.isEmpty())
szCon += "&password=" + szPassword;
}
db = DriverManager.getConnection(szCon);
bConnected = true;
} else {
logger.error("No database name!!");
System.exit(0);
}
} catch(SQLException | ClassNotFoundException e) {
szError = e.getMessage();
e.printStackTrace();
logger.error("Can't connect: %s", e);
}
return logger.exit(bConnected);
}
public void disconnect()
{
logger.entry();
try {
db.close();
bConnected = false;
} catch(SQLException e) {
e.printStackTrace();
logger.error("Can't disconnect: %s", e);
}
logger.exit();
}
public boolean isConnected()
{
return bConnected;
}
public String getError()
{
return szError;
}
public ArrayList<HashMap<String,String>> query(String szQuery)
{
logger.entry(szQuery);
ArrayList<HashMap<String,String>> aResults = new ArrayList<HashMap<String,String>>();
int iCols = 0;
try {
Statement stmt = db.createStatement();
logger.info("Query: %s", szQuery);
ResultSet rs = stmt.executeQuery(szQuery);
ResultSetMetaData rsmd = rs.getMetaData();
iCols = rsmd.getColumnCount();
while(rs.next())
{
HashMap<String,String> pv = new HashMap<String,String>();
for(int i = 0; i < iCols; i++)
{
String szCol = rsmd.getColumnLabel(i + 1);
String szVal = rs.getString(i + 1);
pv.put(szCol, szVal);
}
aResults.add(pv);
}
rs.close();
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
szError = e.getMessage();
logger.error("Error executing query: %s", e);
}
return logger.exit(aResults);
}
public boolean update(String szQuery)
{
logger.entry(szQuery);
boolean bResult = false;
try {
Statement stmt = db.createStatement();
logger.info("Query: %s", szQuery);
stmt.executeUpdate(szQuery);
bResult = true;
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
szError = e.getMessage();
bResult = false;
logger.error("Error executing query: %s", e);
}
return logger.exit(bResult);
}
}
The class Task which all the servlet classes are based on, is a simple abstract class:
package it.metmi.mmasgis.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Task
{
public abstract void doTask(HttpServletRequest request, HttpServletResponse response);
}
The class which throws NullPointerExceptions it this one, during the invocation of db.disconnect(). This class is called rapidly via AJAX 4 or 5 times from the interface written in JS.
package it.metmi.mmasgis.servlet.params;
import it.metmi.mmasgis.servlet.Task;
import it.metmi.mmasgis.utils.Const;
import it.metmi.mmasgis.utils.DBManager;
import it.metmi.mmasgis.utils.Query;
import it.metmi.mmasgis.utils.Utility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClassType extends Task
{
private DBManager db = null;
private Logger logger = LogManager.getFormatterLogger(ClassType.class.getName());
#Override
public void doTask(HttpServletRequest request, HttpServletResponse response)
{
logger.entry(request, response);
String szCensimento = Utility.getParameter(request, "censimento");
String szCategoria = Utility.getParameter(request, "category");
ArrayList<HashMap<String,String>> aClasses = new ArrayList<HashMap<String,String>>();
PrintWriter out = null;
logger.debug("Census: %s", szCensimento);
logger.debug("Category: %s", szCategoria);
db = new DBManager(szCensimento, Const.DB_USER, Const.DB_PASS);
if(db.connect())
{
String szQuery = String.format(Query.classes, szCategoria, szCategoria);
aClasses = db.query(szQuery);
db.disconnect();
}
try {
out = response.getWriter();
jsonEncode(aClasses, out);
} catch(IOException e) {
e.printStackTrace();
logger.error("Failed to encode JSON: %s", e);
}
logger.exit();
}
private void jsonEncode(ArrayList<HashMap<String,String>> aData, PrintWriter out)
{
HashMap<String,Object> result = new HashMap<String,Object>();
result.put("results", aData);
result.put("success", true);
Gson gson = new GsonBuilder().create();
gson.toJson(result, out);
}
}
If the webapp would use only one database, it could be rewritten as a Singleton, but in this way I have no idea on how to handle different connections for different databases.
How can avoid these exceptions?
The problem was that the connection object was declared as member.
Moving the variable inside the methods resolved.
I have created a RESTFUL webservice, witch returns a json, but at this time i only consult and show a simple select * , i need to create a complete CRUD solution, if anyone have some samples to share, i'll appreciate.
Best Regards to all
My code until now are:
DAO - Access.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.Usuarios;
public class Access
{
public ArrayList<Usuarios> getUsuarios(Connection con) throws SQLException
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM usuarios");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Usuarios usuariosObj = new Usuarios();
usuariosObj.setUsr_id(rs.getInt("usr_id"));
usuariosObj.setUsr_login(rs.getString("usr_login"));
usuariosObj.setUsr_pwd(rs.getString("usr_pwd"));
usuariosList.add(usuariosObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return usuariosList;
}
}
DTO - Usuarios.java
package dto;
public class Usuarios
{
private int usr_id;
private String usr_login;
private String usr_pwd;
public Usuarios()
{
}
public Usuarios(int usr_id, String usr_login, String usr_pwd)
{
super();
this.usr_id = usr_id;
this.usr_login = usr_login;
this.usr_pwd = usr_pwd;
}
public int getUsr_id()
{
return usr_id;
}
public void setUsr_id(int usr_id)
{
this.usr_id = usr_id;
}
public String getUsr_login()
{
return usr_login;
}
public void setUsr_login(String usr_login)
{
this.usr_login = usr_login;
}
public String getUsr_pwd()
{
return usr_pwd;
}
public void setUsr_pwd(String usr_pwd)
{
this.usr_pwd = usr_pwd;
}
#Override
public String toString()
{
return "[ {usr_id=" + usr_id + ", usr_login=" + usr_login + ", usr_pwd=" + usr_pwd + "} ]";
}
}
Model - AccessManager.java
package model;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import dao.Access;
import dao.Database;
import dto.Usuarios;
public class AccessManager
{
public ArrayList<Usuarios> getUsuarios() throws Exception
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
usuariosList = access.getUsuarios(con);
return usuariosList;
}
}
WebService - UsuariosService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.google.gson.Gson;
import model.AccessManager;
import dto.Usuarios;
#Path("/UsuariosService")
public class UsuariosService
{
#GET
#Path("/usuarios")
#Produces("application/json")
public String usuarios()
{
String usuarios = null;
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
try
{
usuariosList = new AccessManager().getUsuarios();
Gson gson = new Gson();
//usuarios = gson.toJson(usuariosList);
usuarios = "{\"usuarios\" :" + gson.toJson(usuariosList) + "}";
} catch (Exception e)
{
e.printStackTrace();
}
return usuarios;
}
}
Usually you should ask a specific trouble you have instead of ask for samples. It looks like you have a structured code and all you need is implement all operations exposing as a service.
In case you need a sample, there quite a lot of resources on the web. Something like this: https://code.google.com/p/javaee6-crud-example/
I'll try give you some quick tips below:
WebService - UsuariosService.java
#POST
#Path("/usuarios")
public Response save(Usuario user) {
try {
manager= new AccessManager();
manager.save(user);
return Response.ok("User has been created.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#DELETE
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id) {
try {
manager= new AccessManager();
manager.delete(id);
return Response.ok("User has been deleted.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#PUT
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id, Usuario user) {
try {
manager= new AccessManager();
manager.update(id, user);
return Response.ok("User has been updated.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
If you donĀ“t understand the usage of PUT, DELETE, POST and so on, I recommend you to read HTTP Method Tutorial. There is several discussion regarding this but you might skip it for a while.
I think you might get an idea from here. Your DAO needs to implement methods to perform CRUD interface as well. The link I've added has a very simple sample that might help as well. You might also check this JPA link.
Not sure whether info above helped but I think it is a start since you have to code it in order to understand more about it :)
I am getting the list of datasources configured in context.xml of Tomcat Server using the method below :
public static List<String> getDataSourcesList() {
List<String> dataSourceList = new ArrayList<String>();
try {
if( initialContext == null ) {
initialContext = new InitialContext();
}
NamingEnumeration<NameClassPair> list = ( ( Context )initialContext.lookup( DATASOURCE_CONTEXT ) ).list( "" );
while( list.hasMore() ) {
dataSourceList.add( list.next().getName() );
}
}
catch( NamingException ex ) {
Logger.getLogger( JDBCUtil.class.getName() ).log( Level.SEVERE, null, ex );
}
return dataSourceList;
}
But this method does not work for Weblogic and Websphere Servers.
How can I get the list of datasource names configured on the Weblogic/WebSphere Servers ?
Is there any method to get the list of datasource names ?
For WebSphere Application Server just use dumpNameSpace command line tool located in PROFILE_ROOT\bin
And your code with small modification is working fine in WAS 8.5.5:
try {
InitialContext initialContext = new InitialContext();
NamingEnumeration<NameClassPair> list = ((Context)initialContext.lookup( "jdbc" ) ).list( "" );
while( list.hasMore() ) {
System.out.println(list.next().getName() );
}
}
catch( NamingException ex ) {
ex.printStackTrace();
}
package jms.queue;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class CheckDB {
public CheckDB() {
super();
}
public static void main(String[] args) {
CheckDB checkDB = new CheckDB();
System.out.println(checkDB.listJDBCContextTable());
}
private Context getContext() throws NamingException {
Hashtable myCtx = new Hashtable();
myCtx.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
// myCtx.put(Context.PROVIDER_URL, "t3://172.30.60.76:7001"); //Admin Server
myCtx.put(Context.PROVIDER_URL, "t3://astpdsoam03.auca.corp:8001"); // SOA Cluster
Context ctx = new InitialContext(myCtx);
return ctx;
}
private String checkDataSource(DataSource ds) {
try {
Connection conn = ds.getConnection();
Statement st = conn.createStatement();
st.execute("select sysdate mydate from dual");
st.getResultSet().next();
Date mydate = st.getResultSet().getDate("mydate");
conn.close();
String date = mydate.toString();
if (date.length() == 10 && date.indexOf("-") == 4 &&
date.lastIndexOf("-") == 7) {
return "OK";
} else {
return "NOK";
}
} catch (Exception e) {
return "NOK"; //getStackTrace(e);
}
}
private static String getStackTrace(Throwable e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
private String listJDBCContextTable() {
String output = "<table>";
ArrayList<String> tab = new ArrayList<String>();
String line = "";
try {
tab = listContext((Context)getContext().lookup("jdbc"), "", tab);
Collections.sort(tab);
for (int i = 0; i < tab.size(); i++) {
output += tab.get(i);
}
output += "</table>";
return output;
} catch (NamingException e) {
return getStackTrace(e);
}
}
private ArrayList<String> listContext(Context ctx, String indent,
ArrayList<String> output) throws NamingException {
String name = "";
try {
NamingEnumeration list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = (Binding)list.next();
String className = item.getClassName();
name = item.getName();
// System.out.println("Name : " + name);
if (!(item.getObject() instanceof DataSource)) {
//output = output+indent + className + " " + name+"\n";
} else {
output.add("<tr><td>" + name + "</td><td>" +
checkDataSource((DataSource)item.getObject()) +
"</td></tr>\n");
}
Object o = item.getObject();
if (o instanceof javax.naming.Context) {
listContext((Context)o, indent + " ", output);
}
}
} catch (NamingException ex) {
output.add("<tr><td>" + name + "</td><td>" + getStackTrace(ex) +
"</td></tr>\n");
}
return output;
}
}
I wrote a servlet file SignUp.java and a helper file Updater.java. SignUp gathers the user info from a form filled by the user. Then it sends the info to Updater so that Updater updates the table in the database using the info. But when I fill the form and click submit, nothing changes. The weird thing is that when I wrote a test file and used it to supply the Updater with some dummy values, the table was updated with those dummy values. -
SignUp.java
package com.onlineshopping.web;
import com.onlineshopping.model.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SignUp extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
String[] month = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
InfoHolder userInfo = new InfoHolder();
userInfo.name = req.getParameter("name");
userInfo.email = req.getParameter("email");
userInfo.date = Integer.parseInt(req.getParameter("date"));
userInfo.month = Arrays.asList(month).indexOf(req.getParameter("month")) + 1;
userInfo.year = Integer.parseInt(req.getParameter("year"));
userInfo.pwd = req.getParameter("pwd");
userInfo.subscribe = "n";
try
{
userInfo.subscribe = req.getParameter("subscribe");
}
catch(Exception e)
{}
Updater u = new Updater();
u.update(userInfo);
}
}
InfoHolder just holds the information.
Updater.java
package com.onlineshopping.model;
import java.io.*;
import java.sql.*;
import java.util.*;
public class Updater
{
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String CONNECTION = "jdbc:mysql://localhost/onlineshopping";
public void update(InfoHolder userInfo)
{
try
{
Class.forName(DRIVER);
Properties p = new Properties();
p.put("user","****");
p.put("password","****");
Connection c = DriverManager.getConnection(CONNECTION,p);
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT MAX(userid)+1 FROM user_info");
rs.next();
int id = rs.getInt(1);
PreparedStatement ps = c.prepareStatement("INSERT INTO user_info VALUES (?,?,?,?,?,?,?)");
ps.setInt(1,id);
ps.setString(2,userInfo.name);
ps.setString(3,userInfo.email);
ps.setInt(4,userInfo.date);
ps.setInt(5,userInfo.month);
ps.setInt(6,userInfo.year);
ps.setString(7,userInfo.subscribe);
ps.executeUpdate();
c.close();
}
catch(Exception e)
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("err", true));
out.println("Error: "+ e);
out.close();
}
catch(IOException e)
{}
}
}
}
test.java
import com.onlineshopping.model.*;
public class test
{
public static void main(String[] args)
{
Updater u = new Updater();
InfoHolder xyz = new InfoHolder();
xyz.name = "check";
xyz.email = "checkmail";
xyz.date = 1;
xyz.month = 1;
xyz.year = 2;
xyz.pwd = "pw";
xyz.subscribe = "n";
u.update(xyz);
}
}
The Updater class file keeps throwing - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. But when I run the test class file from the terminal the same Updater class runs smoothly.
Is there a problem with my CLASSPATH variable:
It has this value -
.:/usr/share/java/mysql.jar:/usr/share/java/mysql-connector-java-5.1.16.jar:/usr/lib/tomcat6/lib/servlet-api.jar:classes.
Please Help.
Try to copy mysql-connector-java-5.1.16.jar into /usr/lib/tomcat6/lib/