Database Reference
In-Depth Information
// Connect.java: connect to the MySQL server
import java.sql.* ;
public class Connect
{
public static void main ( String [] args )
{
Connection conn = null ;
String url = "jdbc:mysql://localhost/cookbook" ;
String userName = "cbuser" ;
String password = "cbpass" ;
try
{
Class . forName ( "com.mysql.jdbc.Driver" ). newInstance ();
conn = DriverManager . getConnection ( url , userName , password );
System . out . println ( "Connected" );
}
catch ( Exception e )
{
System . err . println ( "Cannot connect to server" );
System . exit ( 1 );
}
if ( conn != null )
{
try
{
conn . close ();
System . out . println ( "Disconnected" );
}
catch ( Exception e ) { /* ignore close errors */ }
}
}
}
To try Connect.java , locate it under the api directory of the recipes distribution, com‐
pile it, and execute it. The class statement indicates the program's name, which in this
case is Connect . The name of the file containing the program must match this name
and include a .java extension, so the filename for the program is Connect.java . Compile
the program using javac :
% javac Connect.java
If you prefer a different Java compiler, substitute its name for javac .
The Java compiler generates compiled byte code to produce a class file named Con
nect.class . Use the java program to run the class file (specified without the .class exten‐
sion). The program should print two lines indicating that it connected and disconnected
successfully:
Search WWH ::




Custom Search