Output issue whilst using a try statement in JSP - java

My .jsp files are not outputting characters when I use out.println inside a try statement. For example:
out.println("testing123");
try {
connectionDB = DriverManager.getConnection(DATABASE_URL, userDB, passDB);
psDB = connectionDB.prepareStatement(sql);
rsDB = psDB.executeQuery();
out.println("hello");
while(rsDB.next()){
out.println("yay");
}
} catch (Exception errorMessage) {
}
It will output "testing123" to the page but It will not output "hello" why is this, and how do I fix this? All help is appreciated. Remember this is a .jsp page.

You seems to be eating the exception in your try/catch. It seems there is some exception happening in your try block and execution is not reaching to the statement
out.println("hello");
Try to print the stacktrace and correct the code so that execution is successful.

This works so you must have Exception in your Database code.
try{
out.println("hello there!");
}
catch(Exception e ){
e.printStackTrace();
}

I think you have error in your Database code.
try this code
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
............................
......
...
..
.
try {
connectionDB = DriverManager.getConnection(DATABASE_URL, userDB, passDB);
stmt = connectionDB.createStatement();
rs = psDB.executeQuery("SELECT * from tblpost");
while(rs.next()){
out.println(rs.getString("column_Name"));
}
} catch (Exception errorMessage) {
out.println("error");
}
if you find it hard try to watch this Database Connection and JSP Display

Related

NullPointerException in Web Services Client (eclipse)

I am fairly new java web services and I trying to use it to access an oracle database. What my project is trying to do is take the input of a zip code and return the information from the database.
I got a web services client working for an animal type using this tutorial and I am trying to take what I learned from that for my project:
http://javapapers.com/web-service/java-web-service-using-eclipse/
Here is my the code for the main class I am using:
package com.zipws.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import javax.jws.WebService;
//import javax.jws.soap.SOAPBinding;
//import javax.jws.soap.SOAPBinding.Style;
public class ZipWebServiceImpl {
public String cityFinder(String zip) {
Connection con = null;
String str = "";
try{
String user = "IVRDEVUSR";
String pass = "voice001";
String url = "jdbc:oracle:thin:#UIQ-UAT-ORA-02:1521/IVRST01";
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement();
ResultSet rsZip = stmt.executeQuery("SELECT *FROM ZIPLOC WHERE ZIP = " + zip);
while(rsZip.next()){
if(zip.equals(rsZip.getString("ZIP"))){
str = rsZip.getString("CITY");
}
else{
str = "Zip code for city not found!";
}
}
rsZip.close();
stmt.close();
}
catch(SQLException e){
//System.out.println("Connection Failed.");
str = "connection failed";
}
catch(ClassNotFoundException cnfe){
//System.out.println("Unable to load driver.");
str = "Unable to load driver";
}
finally{
try{
con.close();
}
catch(SQLException e){
//System.out.println("Failed to close connection.");
str = "Failed to close connection.";
}
}
return str;
}
}
The web services client classes were generated by Eclipse which I learned to do from the tutorial earlier. When I run the client and enter a zipcode to try to invoke the above class, it returns a NullPointerException and I do not know why. Can anyone possibly explain why?
You should check in the finally block if 'con != null'. Otherwise even in cases the driver could not be loaded you are trying to close the connection which can never succeed.
Debug the method and check what exception occurs. Is maybe the oracle driver missing in the classpath?

how i can add database to the package of netbean project

I want to create a program to use it on any computer , so when i install it must import the database.sql from its place .. so i have to add it to the package of project , but when i did i have a message that's tells (java.sql.SQLException : no such table : table-name) , even though am sure that I have a table there.
so could u tell me where is the problem . or if there is any way to import the database from project folder wherever it was ?
thank you !
import java.awt.*;
import java.sql.*;
import javax.swing.*;
public class dbc {
Connection conn = null;
ResultSet rs = null ;
PreparedStatement pst = null ;
public static Connection ConnecrDb() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:Tab.sqlite");
return conn;
}catch (Exception e ){
JOptionPane.showMessageDialog(null, e)
return null;
}
}
}
and there is a file in the package called Tab.sqlite
Firstly: You should copy/create a database and collect the database location path then when you are try to get a connection, should put the database urlPath into DriverManager.getConnection(urlPath);
Also you can try:
public Connection DBConn() {
String connStr = "jdbc:sqlite:<location path>/myDB.db";
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(connStr);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.exit(2);
}
return conn;
}
I solved the problem , I should write this :
Connection conn = DriverManager.getConnection("jdbc:sqlite:/src/Tab.sqlite");
if I want to import the sql database from package of project I have to add /src/myDB.sqlite
thank you all :D

insert "Finally" to complete the code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i hav written a program in java using both get and set method....but it does not give me the desired output it tells insert finally block my code is given below..in the console of eclipse it shows only connected but no values of table displayed
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.glomindz.mercuri.pojo.User;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public List<User> get_all_data() {
List<User> usersList = new ArrayList<User>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
usersList.add(user);
}
}
}
public List<User> set_all_data() {
List<User> usersList = new ArrayList<User>();
try {
PreparedStatement stmt = connection.prepareStatement("INSERT INTO spl_user_master(name,email,mobile,password,role,status,last_update)VALUES(?,?,?,?,?,?,?)");
stmt.setString(1, "Charlie Sheen");
stmt.setString(2, "help#glomindz.com");
stmt.setString(3, "9554087107");
stmt.setString(4, "cbf91a71c21d5ec348b0c749b2f0055k");
stmt.setString(5, "user");
stmt.setString(6, "3");
stmt.setString(7, "2013-07-02 22:05:16");
boolean execute = stmt.execute();
System.out.println(execute);
stmt.getResultSet();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usersList;
}
public static void main(String[] args) {
UserServicesDAO userdao = new UserServicesDAO();
List<User> data = userdao.get_all_data();
List<User> data1 = userdao.set_all_data();
System.out.println(data);
System.out.println(data1);
System.exit(0);
}
}
whats wrong with the code plz specify
In java, try block must be followed either by a catch or a finally block. In your code you have the below try block, which is not followed by a catch/finally block(s).
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
usersList.add(user);
}
} // missing catch/finally statements
You can either add a catch block to handle any exception happening in the above try block code or put a finally block. The general construct for a try block is
try {
code
}
catch and finally blocks . . .
Learn more about java exception handling here: http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
You can not have only try{ } in Java. try { } block must be followed by either catch{ } or finally{ }.
So here you should use either catch{ } or finnaly{ } for code utilization.
try{
....
....
}finally{
//cleanup
}
try{
....
....
}catch(Exception e)
{
....
....
}
You can also refer this :
http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
You need a catch block if you want to catch exceptions.
try {
....
} catch (Exception e) {
....
}
If you use try and finally combination, note that try is there only to allow finally.
You don't assign stmt.getResultSet(); to anything! UserList is an empty list as nothing is added to it. You need to add the results of stmt.getResultSet(); to the list.
For finally: The code block in finally will be executed for sure - but it is NOT sure when! Use finally to close database connections or other clean up work. Or better, do not use it at all. http://my.safaribooksonline.com/book/programming/java/9780137150021/creating-and-destroying-objects/ch02lev1sec7
Use a catch block to catch errors
You can not have a try block only. To have a try block you must have at least one catch block or a finally block

JDBC + ScriptRunner : error with runScript

I want to use ScriptRunner to execute a sql script file with a JDBC driver.
I can initiate ScriptRunner but I can't execute the runScript line :
ScriptRunner runner = new ScriptRunner(c, false, false);
runner.runScript("C:/Users/Pierre/Documents/create.sql");
The error is :
cannot find symbol method
runScript(java.lang.String) || line 41
The connection with the database is fine.
import java.sql.*;
public class ConnectPostgreSQL {
public static void main(String[] argv) {
System.out.println("Checking if Driver is registered with DriverManager.");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Couldn't find the driver!");
System.out.println("Let's print a stack trace, and exit.");
cnfe.printStackTrace();
System.exit(1);
}
System.out.println("Registered the driver ok, so let's make a connection.");
Connection c = null;
try {
// The second and third arguments are the username and password,
// respectively. They should be whatever is necessary to connect
// to the database.
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "passroot");
} catch (SQLException se) {
System.out.println("Couldn't connect: print out a stack trace and exit.");
se.printStackTrace();
System.exit(1);
}
if (c != null)
System.out.println("Hooray! We connected to the PostgreSQL database!");
else
System.out.println("We should never get here.");
//temps t1
long begin = System.currentTimeMillis();
System.out.println(begin);
ScriptRunner runner = new ScriptRunner(c, false, false);
runner.runScript("C:/Users/Pierre/Documents/create.sql");
//temps t2
long end = System.currentTimeMillis();
System.out.println(end);
//différence de t2 - t1
float time = ((float) (end-begin)) / 1000f;
System.out.println(time);
}
}
Can somebody help me ?
Thanks !
It's because runScript method hasn't in argument String, look to ScriptRunner code
public void runScript(Reader reader)
Change your
runner.runScript("C:/Users/Pierre/Documents/create.sql");
To:
try {
FileReader reader = new FileReader("C:/Users/Pierre/Documents/create.sql");
runner.runScript(reader);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and add imports like
import java.io.BufferedReader;
import java.io.FileReader;
The runScript method of ScriptRunner takes a Reader as an argument, so you need to change line 41 to
try {
runner.runScript(new BufferedReader(new FileReader("C:/Users/Pierre/Documents/create.sql")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
and add imports like
import java.io.BufferedReader;
import java.io.FileReader;
ScriptRunner send line by line to DB. When the script has a delimiter ($$, &&, ||), the line is automatically executed. To fix this, you need to use the last version of ScriptRunner and set to send full script (runner.setSendFullScript(true)).

java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver

I am really new to JAVA but need to call a SQL Server function which I have been given access to.
I have built a JAVA call into a pl/sql function and am successfully calling it from one of my environments. When I move to another environment I get the error
ORA-29532: Java call terminated by uncaught Java exception: java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver
I have researched this to death and checked the correct installation of JAVA which seems fine but I'm obviously missing something. I need to somehow trace what is different on this environment, the fact that it runs in the other envionmnet proves that the class is correct so it has to be a config issue.
JAVA Class
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.net.Socket;
import java.io.IOException;
public class xxiceHJ
{
protected static String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
protected static String DB_URL = "jdbc:sqlserver://999.999.99.99:1433";
protected static String USER = "xxxx";
protected static String PWD = "xxxxx123$";
public static String getOrderStatus (String OrderNumber) throws SQLException, Exception
{
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
String Message = null;
String WarehouseId = "01";
try
{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
//Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PWD);
cs = conn.prepareCall("{call usp_get_order_status(?,?,?)}");
cs.setString(1, WarehouseId);
cs.setString(2, OrderNumber);
cs.setString(3, Message);
rs = cs.executeQuery();
//if prodeure return a value
if (rs.next())
{
Message = rs.getString(1);
}
//Clean-up environment
rs.close();
cs.close();
conn.close();
// }
// catch (SQLException se)
// {
// //Handle errors for JDBC
// cfFileNumber = "SQLException" + se.toString();
// se.printStackTrace();
// }
// catch (Exception e)
// {
// //Handle errors for Class.forName
// cfFileNumber = "Exception" + e.toString();
// e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if (rs!=null)
{
rs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (cs!=null)
{
cs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (conn!=null)
{
conn.close();
}
}
catch (SQLException se)
{
se.printStackTrace();
}
}
return Message;
}
}
The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer. If the drivers are not listed in your CLASSPATH variable, you receive the following error message when you try to load the driver:
java.lang.ClassNotFoundException: com/microsoft/jdbc/sqlserver/SQLServerDriver
The JDBC driver is not part of the Java SDK. If you want to use it, you must set the classpath to include the sqljdbc.jar file or the sqljdbc4.jar file. If the classpath is missing an entry for sqljdbc.jar or sqljdbc4.jar, your application will throw the common "Class not found" exception.
The sqljdbc.jar file and sqljdbc4.jar file are installed in the following location:
\sqljdbc_\\sqljdbc.jar
\sqljdbc_\\sqljdbc4.jar
The following is an example of the CLASSPATH statement that is used for a Windows application:
CLASSPATH =.;C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc.jar
The following is an example of the CLASSPATH statement that is used for a Unix/Linux application:
CLASSPATH =.:/home/usr1/mssqlserverjdbc/Driver/sqljdbc_4.0/enu/sqljdbc.jar
You must make sure that the CLASSPATH statement contains only one Microsoft JDBC Driver for SQL Server, such as either sqljdbc.jar or sqljdbc4.jar.
For more information, please see:
http://support.microsoft.com/kb/313100
http://msdn.microsoft.com/en-us/library/ms378526.aspx
first Please download correct sql driver and then check your are using correct connection driver as per operating system. then once you have to test your connection if its working fine then you will go to next .
so please check this url
microsift sql server driver for linux
https://msdn.microsoft.com/en-us/library/hh568451(v=sql.110).aspx
my sql server driver for linux
https://dev.mysql.com/downloads/connector/j/5.0.html

Categories