I just started using MySQL and I just can see myself woking with strings! I mean the compiler can't catch errors like this and it's just a mess! Is there a wrapper or some kind of class I can add that does something as simple as making 开发者_运维百科a function that adds a table and asks for args?
I'm sure there is a tool like that but I can't find it or know its name.
You're basically looking for an Object Relational Mapper. Hibernate is one of the pioniers in this area. JPA is a new and well-established Java EE standard in this area, formed by the guy behind Hibernate. Hibernate and EclipseLink offers JPA implementations.
There exist IDE tools to autogenerate Java classes based on database models and vice versa, such as Hibernate Tools for "good old" Hibernate and Eclipse Dali for JPA.
If you don't want to use an ORM and/or don't want to autogenerate model objects, then you just have to make sure that you design the right model objects for the database model. I.e. use a Long
property for a BIGINT
field, a BigDecimal
property for a DECIMAL
field, etcetera. You can find an overview of the default mappings in this page.
In "plain vanilla" JDBC you should at least use PreparedStatement
methods to compose the SQL query rather than concatenating as String. There are a lot of setXXX()
methods for the specific datatype, such as setLong()
, setBigDecimal()
, etcetera. The PreparedStatement
not only eases setting fullworthy Java objects like Date
and InputStream
in a SQL query, but it also prevents the code from SQL injection attacks. You can learn more about PreparedStatement
in the Sun JDBC tutorial and you can find a basic kickoff DAO tutorial in this article.
You can use an object-relational mapper like Hibernate. See also What Java ORM do you prefer, and why?.
Give JDBC prepared statements a try.
精彩评论