As a C# developer new to Java, i thought it might be easiest if i simply show a bit of C# code so i can see what the equivalent Java JDBC calls are:
String myConnectionString = "...";
String mySql = "select name from people where id = @myId";
int myId = 123456;
List<Field> fields = new List<Field>();
using (SqlConnection conn = new SqlConnection(myConnectionString)
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(mySql,conn))
{
cmd.Parameters.AddWithValue("@myId", myId);
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
String name = rdr.GetString(0);
fields.Add(name);
}
}
}
}
Now i know that the using statements above will safely close the database if anything goes wrong, whereas with java it’s a bit more complicated (try..finally or something). And in java, i’m not sure what exactly needs to be disposed or closed (or whatever) – the connection only? Or the statement as well?
If you could give me a leg up, that’d be great. Thanks a lot
edit: I really like the code here: (Java Exception Handling – Style)
Connection conn = MyDatabaseLayer.getConnection();
try {
... use conn ...
}
finally {
conn.close();
}
However, do i need to do any further exception handling to ensure the statement and reader and all that other stuff gets closed? Or is closing the connection enough?
Here’s a rough explanation of the steps, as liberally copied from some random page:
first, you load the driver. This will be a class in your driver jar file. In many environments you get this, actually, from a datasource, this is sort of old fashioned, but probably better to see the nuts and bolts.
then you get a connection:
The url string tends to be different for different db vendors. Luckily we don’t swap databases too often, so you only need to look it up once. Now you can finally use the damned thing.
A prepared statement gets cached, so you can use it with inseted parameters. It will work with a plain SQL statement, but for that you can just use a statement. You can also just call conn.executeQuery(…) to get a resultSet, which is what you want.
Now you can loop through the rs, and get whatever:
ResultSets also have ResultSetmetadata which gives you things like the column names, # of columns (but not the total # of results, which would be too easy).
As for try catch, you need to close your statement/result set after you use them. Every time. Otherwise bad things will happen. Like leaving open resources on your db. Since your db connect method can throw errors, you rap the whole thing in a try catch, and close your statement (and connection, if you’ve made it here) in a finally block.
This is why people use ORM frameworks in java.