对列用法 java_Java如何使用列的不同方法对列数进行计数,获取列名称,获取列类型等?...

在Java编程中,Java如何使用列的不同方法对列数进行计数,获取列名称,获取列类型等?假定数据库名称是:testdb,其中有两张表:employee和dept,employee表中有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

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值