Sunday 29 December 2013

How to Connect Java With Mysql in eclipse

Step 1: Download mysql Connector from the link Below.

http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.0.8/mysql-connector-java-5.0.8.jar

Step2: Right Click on project name select properties, then select java Build Path and go to Libraries tab.

Step 3: Click  on add External jar browse to the downloaded mysql-connector jar file then Click ok.
Step 4:  write the following code.

import java.sql.*;

public class ConnectToMySql {
   
    public static void main(String[] args) throws Exception {
   
       Class.forName("com.mysql.jdbc.Driver"); //checking for drivers
//DriverManager.getConnection("jdbc:mysql://servername/database","username","password")
       Connection con =  DriverManager.getConnection("jdbc:mysql://localhost/test","root","");

       Statement st=con.createStatement();
       System.out.println("Connected To MySql 5.0");
       ResultSet rs=st.executeQuery("SELECT * FROM users"); //users table name
       while ( rs.next()) {
           System.out.println( rs.getString("username") + ":" + rs.getString("password"));//username and password are the fields of users table
       }
       con.close();
    }
}

No comments:

Post a Comment