Database Reference
In-Depth Information
{
// construct connection URL, encoding username
// and password as parameters at the end
url = "jdbc:mysql://"
+ props . getProperty ( "host" )
+ "/cookbook"
+ "?user=" + props . getProperty ( "user" )
+ "&password=" + props . getProperty ( "password" );
Class . forName ( "com.mysql.jdbc.Driver" ). newInstance ();
conn = DriverManager . getConnection ( url );
System . out . println ( "Connected" );
}
catch ( Exception e )
{
System . err . println ( "Cannot connect to server" );
}
finally
{
try
{
if ( conn != null )
{
conn . close ();
System . out . println ( "Disconnected" );
}
}
catch ( SQLException e ) { /* ignore close errors */ }
}
}
}
To have getProperty() return a particular default value when the named property is
not found, pass that value as a second argument. For example, to use 127.0.0.1 as the
default host value, call getProperty() like this:
String hostName = props . getProperty ( "host" , "127.0.0.1" );
The Cookbook.java library file developed elsewhere in the chapter (see Recipe 2.3 ) in‐
cludes an extra library call in the version of the file that you'll find in the lib directory
of the recipes distribution: a propsConnect() routine that is based on the concepts
discussed here. To use it, set up the contents of the properties file, Cookbook.proper
ties , and copy the file to the same location where you installed Cookbook.class . You can
then establish a connection within a program by importing the Cookbook class and
calling Cookbook.propsConnect() rather than by calling Cookbook.connect() .
2.9. Conclusion and Words of Advice
This chapter discussed the basic operations provided by each of our APIs for handling
various aspects of interaction with the MySQL server. These operations enable you to
write programs that execute any kind of statement and retrieve the results. Up to this
Search WWH ::




Custom Search