Java如何使用列的不同方法對列數進行計數,獲取列名稱,獲取列型別等?

2019-10-16 22:26:09

在Java程式設計中,Java如何使用列的不同方法對列數進行計數,獲取列名稱,獲取列型別等?假定資料庫名稱是:testdb,其中有兩張表:employeedeptemployee表中有4條記錄,dept表中有2條記錄。

建立資料庫表的語句 -

use testdb;
-- 員工表
drop table if exists employees;
create table if not exists employees (
  id int not null primary key,
  age int not null,
  name varchar(64),
  dept_id int(10)
);
INSERT INTO employees VALUES (100, 28, 'MaxSu', 1);
INSERT INTO employees VALUES (101, 25, 'WeiWang', 2);
INSERT INTO employees VALUES (102, 30, 'KidaSu', 2);
INSERT INTO employees VALUES (103, 28, 'KobeBryant', 1);
----
-- 部門表
drop table if exists dept;
create table if not exists dept (
  id int not null primary key,
  name varchar (64)
);
INSERT INTO dept VALUES (1, '技術部');
INSERT INTO dept VALUES (2, '市場部');

以下範例使用getColumnCount()getColumnName()getColumnTypeName()getColumnDisplaySize()方法來獲取列的列號,列的名稱或列的型別。

package com.yiibai;

import java.sql.*;

public class UseColumnMethods {
    public static void main(String[] args) throws Exception {

        String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        String DB_URL = "jdbc:mysql://localhost/testdb?useSSL=false";
        String User = "root";
        String Passwd = "123456";
        Connection con = null;
        Statement stmt = null;
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        try {

            con = DriverManager.getConnection(DB_URL, User, Passwd);
            stmt = con.createStatement();
            String query = "select * from employees order by name";

            ResultSet rs = stmt.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            System.out.println("no of columns in the table = " + rsmd.getColumnCount());
            System.out.println("Name of the first column " + rsmd.getColumnName(1));
            System.out.println("Type of the second column " + rsmd.getColumnTypeName(2));
            System.out.println("No of characters in 3rd column " + rsmd.getColumnDisplaySize(2));
        } catch (

        SQLException e) {
            System.out.println("SQL exception occured" + e);
        }

    }
}

上述程式碼範例將產生以下結果。

no of columns in the table = 4
Name of the first column id
Type of the second column INT
No of characters in 3rd column 11

註:如果JDBC驅動程式安裝不正確,將獲得ClassNotfound異常。

Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
JDBC Class found
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/testdb