zoukankan      html  css  js  c++  java
  • 在Eclipse中用JDBC连接Mysql数据库

    一、配置要求

    二、安装

             JDK、Mysql、Eclipse的安装就不赘述了,解压缩到你放JDBC驱动程序的位置就可以了,不需要安装。然后设置Classpath环境变量,在Classpath环境变量里添加JDBC驱动程序,如我的是添加D:Work Softwaremysql-connector-java-5.0.8mysql-connector-java-5.0.8-bin.jar 。注意,要是用Eclipse运行java文件时要在配置路径下添加mysql-connector-java-5.0.8-bin.jar文件。步骤为:右键你要添加的项目-->Build path-->Configure Build path..-->Libraries-->Add External Jars然后选择文件所在路径。

    三、建立数据库

           用数据库管理软件(我是用Navacat)建立数据库,演示中数据库名称为school,students表,表中包括ID,Name,Age字段。

    四、编写代码

    import java.sql.*;
    
    public class JDBCTest {
    
    public static void main(String[] args){
           // 驱动程序名
           String driver = "com.mysql.jdbc.Driver";
           // URL指向要访问的数据库名school
           String url = "jdbc:mysql://127.0.0.1:3306/school";
           // MySQL配置时的用户名
           String user = "root";
           // MySQL配置时的密码
           String password = "123456";
           try {
            // 加载驱动程序
            Class.forName(driver);
            // 连续数据库
            Connection conn = DriverManager.getConnection(url, user, password);
            if(!conn.isClosed())
             System.out.println("Succeeded connecting to the Database!");
            // statement用来执行SQL语句
            Statement statement = conn.createStatement();
            // 要执行的SQL语句
            String sql = "select * from students";
            // 结果集
            ResultSet rs = statement.executeQuery(sql);
            System.out.println("-----------------");
            System.out.println("执行结果如下所示:");
            System.out.println("-----------------");
            System.out.println(" 学号" + "	" + " 姓名");
            System.out.println("-----------------");
            String name = null;
            while(rs.next()) {
             // 选择Name这列数据
             name = rs.getString("Name");
             // 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
             // 然后使用GB2312字符集解码指定的字节数组
             name = new String(name.getBytes("ISO-8859-1"),"GB2312");
             // 输出结果
             System.out.println(rs.getString("ID") + "	" + name);
            }
            rs.close();
            conn.close();
           } catch(ClassNotFoundException e) {
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
           } catch(SQLException e) {
            e.printStackTrace();
           } catch(Exception e) {
            e.printStackTrace();
           }
    }
    }

    参考:http://www.cnblogs.com/soplayer/archive/2007/06/26/796565.html

      

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    L3-013. 非常弹的球
    L2-020. 功夫传人
    L1-039. 古风排版
    Innobackup备份过程
    MySQL物理备份的过程
    数据库表设计
    MySQL启动排错
    redo的类型和作用
    描述undo的三个作用
    redo log和binlog的纠缠
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734117.html
Copyright © 2011-2022 走看看