Thursday 13 March 2014

java database connectivity code with mysql example

 Create database in mysql as:- aavikme.

   import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;
    
    public class MySQLConnectExample {
    static
      {
        try
        {
          // loads com.mysql.jdbc.Driver into memory
          Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException cnf)
        {
          System.out.println("Driver could not be loaded: " + cnf);
        }
      }
    
        public static void main(String[] args) {
    
            // creates three different Connection objects
            Connection conn1 = null;
            Connection conn2 = null;
            Connection conn3 = null;
     try {
               Class.forName("com.mysql.jdbc.Driver");
   
                // connect way #1
                String url1 = "jdbc:mysql://localhost:3306/aavikme";
                String user = "root";
                String password = "your password";
   
                conn1 = DriverManager.getConnection(url1, user, password);
                if (conn1 != null) {
                    System.out.println("Connected to the database test1");
                }
   
                // connect way #2
                String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=your password";
                conn2 = DriverManager.getConnection(url2);
                if (conn2 != null) {
                    System.out.println("Connected to the database test2");
                }
   
                // connect way #3
                String url3 = "jdbc:mysql://localhost:3306/aavikme";
                Properties info = new Properties();
                info.put("user", "root");
                info.put("password", "your password");
   
                conn3 = DriverManager.getConnection(url3, info);
                if (conn3 != null) {
                    System.out.println("Connected to the database test3");
                }
       } catch (SQLException ex) {
                System.out.println("An error occurred. Maybe user/password is invalid");
                ex.printStackTrace();
       } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     }     







    
save it as MySQLConnectExample.java
DONE IT

Run it in cmd

E:\java mysql code driver>javac MySQLConnectExample .java

E:\java mysql code driver>java -cp . MySQLConnectExample

SAVE ALL FILE AS SHOWN IN PIC.


No comments:

Post a Comment