Compile Connect.java to produce a class file Connect.class that contains executable Java code:
% javac Connect.java
Then invoke the class file as follows and it should connect to and disconnect from your MySQL server:
% java Connect
Database connection established
Database connection terminated
If you have trouble compiling Connect.java, double check that you have a Java Software Development Kit installed and make sure that the MySQL Connector/J driver is listed in your CLASSPATH environment variable.
The arguments to getConnection() are the connection URL and the user name and password of a MySQL account. As illustrated by Connect.java, JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of the MySQL server host and the database name. An alternate syntax for specifying the user and password is to add them as parameters to the end of the connection URL:
jdbc:mysql://localhost/test?user=testuser&password=testpass
When you specify a URL using this second format, getConnection() requires only one argument. For example, the code for connecting to the MySQL server in Connect.java could have been written like this:
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test?user="
+ userName
+ "&password="
+ password;
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url);
getConnect() returns a Connection object that may be used to interact with MySQL by issuing queries and retrieving their results. (The next section describes how to do this.) When you're done with the connection, invoke its close() method to disconnect from the MySQL server.
To increase the portability of your applications, you can store the connection parameters (host, database, user name, and password) in a Java properties file and read the properties at runtime. Then they need not be listed in the program itself. This allows you to change the server to which the program connects by editing the properties file, rather than by having to recompile the program.