Some Java and MySQL Connector/J tips

No Comments

Ok, I and others have been bitten by some of these oversights so I hope it will be of some use to some:

1. Dont use the jar file ending with -g. That will require the aspectj libraries which is a paradigm for simplifying inclusion of boiler plate code (e.G. Debugging, etc.). Use the other one.

2. At least in the development phase: DO NOT WANTONLY OVERRIDE EXCEPTION MESSAGES AND STACKTRACES. They may seem ugly but they have their purposes. Handle the exceptions but output the error somewhere to help you debug. You can remove the debugging statement later.

As an added tip, use a unique word to tag statements that you will remove later (e.g. prepending System.out.println messages with “[REMOVE]”) to facilitate search and remove later on. Or use the task feature of Eclipse if you are using it (i.e. start a comment with “//TODO” and it will appear in the task list) .

3. Use PreparedStatement calls whenever possible. However, DO NOT USE them when executing SQL INSERT statements with embedded SELECT statements. Construct your SQL statement via plain-jane string manipulation and execute them with Statement objects.

When constructing SQL statements for PreparedStatement objects, escaping strings that will be dynamically specified are not required. Just make sure that the question marks have spaces before and after.

4. The latest MySQL Connector/J drivers require JRE 1.4.x. Aside from that, aim for the lowest JDK possible to ensure maximum compatiblity. Java Runtime Environments are usually backward-compatible.

5. Modularize your code. This way you can do unit tests on your methods before integrating them to the main code structure.

6. Maximize comments. Make sure you create comments for all methods (no matter what the scope is) to describe what it needs to do. It is also good to create multi-line comments on how you would proceed in the body of the method. It gives focus on what you need to do and what will come after it.

I’ll just post additional ones as I encounter them.

ciao!