Eclipse连接MySQL数据库

今年自从开始了AS3开发,感觉离java越来越远了,竟然连基本的连接数据库都要查资料了。。。不说了,自己学一篇吧。

在开发之前先开下载安装mysql吧,安装方法:http://www.duote.com/tech/1/2430_1.html

安装好之后,就可以利用myEclipse或者intellij IDEA进行数据库的开发了。但是在连接数据库之前首先需要有一个数据库驱动程序,就是Java的jar包。

可以到这里下载Java的mysql的驱动包:http://download.csdn.net/detail/weierbufan/8396207

1、导入数据库驱动:

打开Eclipse,创建一个项目(my),

操作:右键点击my--->build Path--->add external Archiver...选择jdbc驱动,点击确定。

在项目列表中可以看到:

2、验证数据库是不是已经连接可用了。。程序如下:

import java.sql.*;
public class TestJDB {
  public static void main(String args[]) {
    try {
      Class.forName("com.mysql.jdbc.Driver");     //加载MYSQL JDBC驱动程序   
      //Class.forName("org.gjt.mm.mysql.Driver");
     System.out.println("Success loading Mysql Driver!");
    }
    catch (Exception e) {
      System.out.print("Error loading Mysql Driver!");
      e.printStackTrace();
    }
    try {
      Connection connect = DriverManager.getConnection(
          "jdbc:mysql://localhost:3306/tx","root","126");
           //连接URL为   jdbc:mysql//服务器地址/数据库名  ,后面的2个参数分别是登陆用户名和密码

      System.out.println("Success connect Mysql server!");
      Statement stmt = connect.createStatement();
      ResultSet rs = stmt.executeQuery("select * from myclass");
                                                              
while (rs.next()) {
        System.out.println(rs.getInt(1)+"	"
                +rs.getString(2)+"	"
                +rs.getInt(3)+"	"
                +rs.getDouble(4)+"	"
                +rs.getInt(5));
      }
    }
    catch (Exception e) {
      System.out.print("get data error!");
      e.printStackTrace();
    }
    
  }
}

运行上面的程序会看到如下的结果:

说明数据库已经连接成功。。

原文地址:https://www.cnblogs.com/duhuo/p/4249221.html