problems with connection to mysql database
When i try to execute the ListProdQty method it jumps from that method to the catch in the connecttodatabase method and gives me a java.lang.NullPointerException
Code :
public void ConnectToDatabase()
{
try
{
String user, pass, host;
user = readEntry("Please enter User ID : ");
pass = readEntry("Please enter Password : ");
host = readEntry("Please enter Hostname : ");
// database = readEntry("Please enter database name: ");
// userid, password and hostname are obtained from the console
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/oncs", user, pass);
/* JDBC default is to commit each SQL statement as it is sent to the database. Setting autocommmit=false changes the default
behaviour so that transactions have to be committed explicity.
*/
conn.setAutoCommit(false);
MenuMain();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
private void ListProdQty()
{
try
{
// Creates a statement and a result set to execute the sql query.
s = conn.createStatement();
resultSet = s.executeQuery("SELECT pname FROM product"+
"WHERE pqtyinstock >5"+
" AND pretailprice > 150"+
"ORDER BY pname");
//Creates a loop to loop through the result set
while(resultSet.next())
{
//Prints the results to the user
System.out.println(resultSet.getString(1));
}
//Commits the connection to the database
conn.commit();
}
catch(SQLException excep)
{
//Prints an error message to the user
System.out.println(excep);
}
}
Re: problems with connection to mysql database
Hey thepower,
First of all, welcome to the forum :)
And then youre code; I see in ListProdQty() that you call conn.createStatement() but! I dont see what conn is actually holding (and think this is part of youre problem).
In ConnectToDatabase() I do see you defining conn as a Connection with a connection provided by the Drivermanager. But! I dont see you putting conn into a attribute of the class or a way that conn in ListprodQty() knows that it was defined in ConnectToDatabase(). Try fixing this first.