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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s