This is my CreateQuery.java class .
package DbConnect;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CreateQuery {
Connection conn;
public CreateQuery() throws ClassNotFoundException, SQLException, IOException {
conn=new DbAccess().returnDatabaseConnection();
}
public int addNewLayertoDB(){
try {
PreparedStatement statement = null;
//String table_name = feature_name + "_" + shape;
String query = "SELECT the_geom from bbmp ";
statement = conn.prepareStatement(query);
//statement.setString(1, feature_name);
ResultSet rs = statement.executeQuery();
rs.close();
return 1;
} catch (SQLException ex) {
System.out.println("Sql exception");
return 0;
}
}
public void closeConn() throws SQLException {
if (conn != null) {
this.conn.close();
}
}
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
CreateQuery cq = new CreateQuery();
cq.addNewLayertoDB();
cq.closeConn();
}
}
This is my DbConnect class
package DbConnect;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DbAccess{
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL " +
"JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/Ethermap","postgres", "*******");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null){
System.out.println("You made it, take control your database now!");
}else{
System.out.println("Failed to make connection!");
}
}
public Connection returnDatabaseConnection() {
System.out.println("DB not connected");
return null;
}
}
The error I am getting when I run CreateQuery is
DB not connected
Exception in thread "main" java.lang.NullPointerException
at DbConnect.CreateQuery.addNewLayertoDB(CreateQuery.java:24)
at DbConnect.CreateQuery.main(CreateQuery.java:45)
What is the error ? And How do I debug it ?
The method returnDatabaseConnection() that you call in the constructor of CreateQuery always returns null, so it's not a surprise that your connection object is null.
Related
I want to get the list of all database names from a Sybase DB server. I can connect the Sybase db through Java, but don't know how to get the list of database names. I am using jconn4 jar file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
I found myself a working code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
List<String> dbList = new ArrayList<String>();
// getting list of DB names from the DB server
ResultSet rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
dbList.add(rs.getString(1));
}
for (String list : dbList) {
System.out.println(list);
}
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
I am a student learning JSP, and I seem to have this issue in executing a method via an object of a DAO class. When the database connectivity and SQL query is given on the servlet itself it, it will work. But when given in the DAO class and a object is used, it doesn't work. Please help.
import dataaccessobjects.cartDAO1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class addtoCartServ extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
cartDAO1 newcart = new cartDAO1();
PrintWriter out = response.getWriter();
if (request.getParameter("submit") != null){
//out.println("added to cart");
try {
//out.println("submit not null");
String Uname = (String) request.getSession().getAttribute("Welcome");
String ino = request.getParameter("ino");
String iqnty = request.getParameter("quantity");
String iname = request.getParameter("iname");
if(newcart.addToCart(iname,Uname,ino,iqnty)){
out.println("added to cart");
}
} catch (SQLException ex) {
Logger.getLogger(addtoCartServ.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(addtoCartServ.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
The DAO class
public cartDAO1(){
}
public boolean addToCart(String iname,String username, String ino,String iqnty) throws SQLException, ClassNotFoundException{
boolean flag = false;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/styleomega","root","");
PreparedStatement ps = conn.prepareStatement("INSERT INTO cart(iname,uname,ino,iqnty) VALUES (?,?,?,?)");
// set the values for parameters
ps.setString(1,iname);
ps.setString(2,username);
ps.setString(3,ino);
ps.setString(4,iqnty);
int rs = ps.executeUpdate();
if (rs==1){
flag = true;
}
return flag;
}
}
You should be import the DAO class package in servlet then access it it will work like
import DAO.cartDao;
If you will not import then how to acces it
I don't understand exactly what is not working? But I have noticed, you're not closing statement and the database connection in your DAO class.
FYI: An example
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
I want to get the values from a table using db2 and print out the results.
This is the code I am trying to use to do that:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class connection {
public static void main(String[] argv) {
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Please include Classpath Where your DB2 Driver is located");
e.printStackTrace();
return;
}
System.out.println("DB2 driver is loaded successfully");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset=null;
boolean found=false;
try {
conn = DriverManager.getConnection("jdbc:db2:sabarish","db2admin","Murugasaranam");
if (conn != null)
{
System.out.println("DB2 Database Connected");
}
else
{
System.out.println("Db2 connection Failed ");
}
pstmt=conn.prepareStatement("SELECT * FROM SYSCAT.COLUMNS WHERE TABSCHEMA= 'STD' AND TABNAME= 'inventory'");
rset=pstmt.executeQuery();
if(rset!=null)
{
while(rset.next())
{
found=true;
System.out.println("Class Code: "+rset.getString("clcode"));
System.out.println("Name: "+rset.getString("name"));
}
}
if (found ==false)
{
System.out.println("No Information Found");
}
} catch (SQLException e) {
System.out.println("DB2 Database connection Failed");
e.printStackTrace();
return;
}
}
}
It only prints out column names. Instead of column names, what query statement can I use to get the results? db2 select * from store.inventory
does not seem to work as well.
Try select * from STD.inventory
I was trying to connect mysql database in my servlet. Then I'm getting an exception.But when I am testing the database connection from a usual Java class the connection is ok and I getting the data from the database.The exception I'm getting on tomcat server console is:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver .
The code of my DatabaseHandler.java is:
import java.sql.*;
public class DatabaseHandler {
private Statement stmt;
private Connection con;
String username = "root";
String password = "thunder";
String dbname = "bidderboy";
public DatabaseHandler()
{
this.createConnection();
}
private void createConnection()
{
//create the connection for first time
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
stmt = con.createStatement();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public int executeUpdate(String sql)
{
int result = 0;
//before update checks if connection is open
try {
if(con.isClosed()) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
stmt = con.createStatement();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
//try to executeUpdate the sql command
try{
result = stmt.executeUpdate(sql);
}
catch(Exception ex){
System.out.println("Couldn't executeUpdate sql command");
}
return result;
}
public ResultSet executeQuery(String sql)
{
ResultSet rs = null;
//before Query checks if connection is open
try {
if(con.isClosed()) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbname , username , password);
stmt = con.createStatement();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
//try to executeQuery the sql command
try{
rs = stmt.executeQuery(sql);
}
catch(Exception ex){
System.out.println("Couldn't executeQuery sql command");
}
return rs;
}
public void closeConnection()
{
//if connection is open try to close the connection
try {
if(!con.isClosed()) {
con.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close database connection");
}
}
}
The code of my servlet is:
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
public class UserLogin extends HttpServlet{
public UserLogin()
{
}
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DatabaseHandler dbh = new DatabaseHandler();
String username="mamun";
String password="1234";
String dbusername="";
String dbpassword="";
String sql = "select * from users where username='"+username+"' and password='"+password+"'";
ResultSet rs = dbh.executeQuery(sql);
try {
while(rs.next())
{
dbusername = rs.getNString(1);
dbpassword = rs.getNString(2);
}
} catch (SQLException e) {}
System.out.println(dbusername+" "+dbpassword);
}
}
And the Code of normal java class from which I'm getting my data is:
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseConnectionTest {
public static void main(String[] args) {
String sql = "Select * from users";
DatabaseHandler dbh = new DatabaseHandler();
ResultSet rs = dbh.executeQuery(sql);
try {
while(rs.next())
{
String n = rs.getNString(1);
String c = rs.getNString(2);
System.out.println("Name: "+n+" Contact: "+c);
}
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
}
Anybody please explain why I'm getting this class not found exception and What can be the solution. Thanks in advance.
Adding mysql-connector-java-5.1.11-bin.jar file to WEB-INF/lib folder fixed my problem.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
i am a beginner in java i am trying to use mysql database i have downloaded mysql-connector-java-5.1.23-bin.jar file from mysql.com and i have added this jar file to in my build path of my project but there is an error in the following code
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
package com.example.demo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}
}
Wrong classes
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
should be
import java.sql.Connection;
import java.sql.Statement;
In fact, java decouples everything from a specific database engine. One never should need an import of MySQL (or ProgressSQL or ...) classes.
To have those classes available at run-time, the first thing after the try, before getting the connection would be:
Class.forName("com.mysql.jdbc.Driver");
This technique would allow reading all strings from a configuration file, and writing database independent code.
Missing: conn = ...
conn = DriverManager.getConnection(CONN_STR, userName, userpwd);
package com.example.demo;
import java.sql.*;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}