Tuesday, September 30, 2008

JDBC connectivity with MySQL

import java.sql.*;
public class MySQLConn {

public static void main(String[] args) {
System.out.println("MySQL Connect Example.");

Connection conn = null;
String url = "jdbc:mysql://localhost:3306/mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";

try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,userName,password);
Statement stmt= conn.createStatement();
System.out.println("Connected to the database ");
String query="select * from mytab";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
-----------------------------------------------------
Note : We need to add a jar to the classpath.
ie., for Oracle - ojdbc14.jar
     for MySQL -  "mysql-connector-java-3.1.12-bin"

In the above code : mydb is the database name

Java - main() method - in shot

Let us think about

public static void main(String args[]){
}

here,
public - specified for java interpreter to access the class
from out side of the class.
static - we need to call main() method before the object creation
of that class.
instance methods can be called after instantiating the class
and by using object reference variable.
void - main() method which return nothing to caller JVM
args[] - this is a String array ,which is used for giving inputs
to our program while running is
eg: java SampleClass Kalathuru Thanooj JavaTemple
for( int i=0; i
System.out.println(args[i]);
}

Note: we can also override the main() method.