MySQL – JDBC connection example

—– Connect.java —-
—- To compile c:> javac Connect.java
—- Note: Make sure the CLASSPATH env is set. MySQL Connnector/J can be downloaded from http://dev.mysql.com/downloads/connector/
—- Example: CLASSPATH=mysql-connector-java-5.1.7\mysql-connector-java-5.1.7-bin.jar;.
—- To run c:> java Connect

— Connect.java code
import java.sql.*;

public class Connect {
public static void main(String argv[]) throws Exception {
Connection conn = null;
try {
String url = “jdbc:mysql://localhost:3306/test?user=root&password=root”;
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
conn = DriverManager.getConnection(url);
if ( conn != null )
System.out.println(“A connection to DB has been made”);

}
catch(Exception e)
{
throw e;
}
finally {
if ( conn != null )
conn.close();
conn = null;
}
}
}

Leave a Reply