>

Saturday, February 23, 2013

Simple java program for connecting to DATABASE(mysql)

In order to connect to database you need to add mysql-connector-java-5.1.22.jar file in your eclipse project as a external jar file....

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlSample {

    /**
     * @param args
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws SQLException
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
        // TODO Auto-generated method stub
        Connection con;
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/saran","root","root");
        Statement stmt;
        ResultSet rs;
        stmt=con.createStatement();
        rs=stmt.executeQuery("select * from employee;");
       
        while(rs.next())
        {
            System.out.println(rs.getString("empname")+rs.getInt("salary"));
        }
    }

}

No comments:

Post a Comment

Please post your comments. Your comments make us to write more programs for you.