Hi, 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: (http://stackoverflow.com/questions/1909662/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?