将MySQL工作台连接到Eclipse

时间:2014-03-04 10:24:57

标签: android mysql eclipse

我是编程新手,从未使用过MySQL,所以请耐心等待!我正在尝试将MySQL工作台连接到我的eclipse项目,但我不知道从哪里开始。有人可以解释一下我需要经历的流程以及如何实施这些流程吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

在Eclipse中创建一个java项目

创建包名称com.example.sql

在项目中加入mysqlconnector.jar

package com.example.sql;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCExample {
    public static Connection con;
  public static void main(String[] argv) {
      try
        {
            connectionQuery();

            PreparedStatement statement =  con.prepareStatement("SELECT * from table_name");/*write query inside of prepared statement*/
            ResultSet result = statement.executeQuery();
            System.out.println("DataBase table accessed");

            while(result.next())
            {
               String retrievedid= result.getString("Column_name");

               System.out.println(retrievedid);
            }


            con.close();
        }

        catch(Exception e)
        {
            e.printStackTrace();
            System.out.println(e.getMessage().toString());
        }
  }

  public static void connectionQuery()
  {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/boopathi","root","root");
            System.out.println("Remote DB connection established");
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("Remote server could not be connected");
        }
        catch (NullPointerException e)
        {
            e.printStackTrace();
            System.out.println("Remote server could not be connected");
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            System.out.println("Remote db connection establishment error");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("False query");
        }
    }
}

Refer this link also