Reputation: 26001
I'm learning Java and just started playing around with mysql and am having a bit of a problem with some logic that worked in python and I'm having trouble converting.
I basically have a try statement that tries to search if a record exists in a database..If it does then great, it moves on but if the record does not exist then it added it. Here's my code
try
{
PreparedStatement Findstatement;
Findstatement = con.prepareStatement(" SELECT DataMaster_MasterCode FROM Allocation WHERE Master_Code = (?) and date = (?)");
Findstatement.setInt(1, Code);
Findstatement.setString(2, AllocationDate);
ResultSet CodeAll = Findstatement.executeQuery();
int DataMaster_MasterCode;
while (CodeAll.next())
{
DataMaster_MasterCode = CodeAll.getInt("DataMaster_MasterCode");
}
System.out.println("Found allocation " + DataMaster_MasterCode + " already exists for " + Name);
}
catch (Exception e)
{ //Create statements... }
The problem is it keeps going to the exception because the DataMaster_MasterCode variable may not be may not be initialized. I think because python just executes the code as it goes along it works in python but because java precompiles it, it sees this as an error and skips. If the variable is not may not be initialized I want it to fail and go to the catch statement(which creates the variable).
Right now it keeps failing and keeps creating(duplicating) entries because it never finishes the statement to find the data itself. I thought about putting an else if statement that checks of the variable is null and then breaks but it didn't work for me either.
Please help me with the logic.
Upvotes: 1
Views: 184
Reputation: 88707
You first have to assign null to the variables, otherwise you'd get an exception as well. Note that local variables are not initialized to any default, so do DataMaster_MasterCode = 0;
etc.
Upvotes: 1
Reputation: 2894
You should use exception handling only for exceptional cases. Checking for an uninitialized value is not one of them. To check for a null value in Java, simply use (variable == null).
Upvotes: 5