eclipse怎么连接mysql数据库

如题所述

你说的是Java吧,原版eclipse本身没有连接mysql数据库的功能,myeclipse这些带插件的才有连接数据库的功能。

http://jingyan.baidu.com/article/4e5b3e196758ad91901e24a0.html这里有myeclipse连接mysql数据库方法。

如果是java的话,先去官网下载mysqlJDBC驱动,然后引入JDBC驱动。

import java.sql.*;
 
public class TestMySql {
  static Connection con = null; // 声明Connection对象
  static Statement sql = null;
  static ResultSet res = null;
 
  public static void main(String[] args) {
    TestMySql c = new TestMySql();
    con = c.getConnection();
    try {
      sql = con.createStatement();
      res = sql.executeQuery("select * from dept");
      while (res.next()) {
        System.out.print(res.getString(1) + "<——>");
        System.out.print(res.getString(2) + "<——>");
        System.out.print(res.getString(3));
        System.out.println();
      }
 
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (res != null) {
          res.close();
          res = null;
        }
        if (sql != null) {
          sql.close();
          sql = null;
        }
        if (con != null) {
          con.close();
          con = null;
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
 
  }
 
  public Connection getConnection() {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      // 加载mysqlJDBC驱动
      System.out.println("数据库驱动加载成功");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    try {// 通过访问数据库的URL获取数据库连接对象
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata", "root", "qwer1234");
      System.out.println("数据库连接成功");
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return con; // 按方法要求返回一个Connection对象
  }
 
}

温馨提示:答案为网友推荐,仅供参考