📜  JDBC中使用Column的方法获取列名的Java程序

📅  最后修改于: 2022-05-13 01:54:40.339000             🧑  作者: Mango

JDBC中使用Column的方法获取列名的Java程序

Java Database Connectivity 或 JDBC 是一种Java API(应用程序编程接口),用于通过Java应用程序执行数据库操作。它允许为 通过Java应用程序创建表和数据操作。 Java支持Java.sql 包,其中包含用于访问和处理存储在数据库中的数据的内置方法。 Java.sql 中的方法会抛出 SQL 异常,因此代码块必须要么放在 try 块中,要么让 catch 块处理异常(如果有的话)向 main 方法添加 throws 子句。

程序:

  1. forName()是类的静态方法,用于加载驱动程序。
  2. 接下来,使用 DriverManager 类的getConnection()方法建立到数据库的连接。 getConnection()接受 URL、用户名和密码来建立连接。 Statement 接口中定义的方法用于与数据库交互。
    • 首先,创建表,然后将记录插入到表中。
    • sql 命令使用addBatch()一起批处理,并使用executeBatch()方法一次执行。
    • 表中的记录被提取到 ResultSet 中。
    • ResultSet 的getMetaData()方法用于获取获取到 ResultSet 中的记录的元数据。
    • ResultSetMetaData 接口的getColumnCount()getColumnName()方法用于获取表中的列数和每列的名称。

示例 1:

Java
// Java Program to Use Methods of Column
// to get column name in JDBC
 
// Step 1: Importing DB files
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
 
// Class to get columns
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        try {
 
            // Step 2: Loading and registering drivers
 
            // Loading driver class
            // using forName() method
            Class.forName("oracle.jdbc.OracleDriver");
 
            // Step 3: Establishing te connection
 
            Connection con = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe",
                "username", "password");
            Statement s = con.createStatement();
 
            // Step 4: Create a statement
            String sql1
                = "CREATE TABLE ACADEMY(COURSE_ID VARCHAR2(20) PRIMARY KEY, COURSE_NAME VARCHAR2(20),MENTOR VARCHAR2(20),COURSE_FEE NUMBER)";
 
            // Step 5: Process the query
            // Inserting records in the table
            String sql2
                = "INSERT INTO ACADEMY VALUES('C101','MATH','ROBERT',5000)";
            String sql3
                = "INSERT INTO ACADEMY VALUES('C102','PHYSICS','JANE',8000)";
            String sql4
                = "INSERT INTO ACADEMY VALUES('C103','HISTORY','ADAM',6000)";
            String sql5
                = "INSERT INTO ACADEMY VALUES('C104','BIOLOGY','MARIE',5000)";
            String sql6
                = "INSERT INTO ACADEMY VALUES('C105','ENGLISH','ALBERT',3000)";
            s.addBatch(sql1);
            s.addBatch(sql2);
            s.addBatch(sql3);
            s.addBatch(sql4);
            s.addBatch(sql5);
            s.addBatch(sql6);
 
            // Step 6: Execute the statements
            // executing the sql commands
            s.executeBatch();
 
            // Obtaining the resultset
            ResultSet rs
                = s.executeQuery("SELECT * FROM ACADEMY");
 
            while (rs.next()) {
 
                System.out.println(
                    rs.getString(1) + "\t\t"
                    + rs.getString(2) + "\t\t"
                    + rs.getString(3) + "\t\t"
                    + rs.getString(4));
            }
 
            // Retrieving the ResultSetMetadata object
            ResultSetMetaData rsMetaData = rs.getMetaData();
            System.out.println(
                "List of column names in the current table: ");
 
            // Retrieving the list of column names
            int count = rsMetaData.getColumnCount();
 
            for (int i = 1; i& lt; = count; i++) {
                System.out.print(rsMetaData.getColumnName(i)
                                 + "\t");
            }
 
            // Step 7: Close the connection
            con.commit();
            con.close();
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Print the exception
            System.out.println(e);
        }
    }
}


Java
// Java Program to Use Methods of Column
// to get column name in JDBC
 
// Step 1: Importing DB files
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Try block to check if exception occurs
        try {
 
            // Step 2: Loading and registering drivers
 
            // Loading driver class
            // using forName() method
            Class.forName("oracle.jdbc.OracleDriver");
 
            // Step 3: Establish a connection
 
            // Create connection object
            Connection con = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe",
                "cse", "cse");
            Statement s = con.createStatement();
 
            // Step 4: Create a starement/s
            // create table
            String sql1
                = "CREATE TABLE STUDENT(STUDENTID VARCHAR2(20) PRIMARY KEY, NAME VARCHAR2(20), DEPARTMENT VARCHAR2(10))";
            // insert records in the table
            String sql2
                = "INSERT INTO STUDENT VALUES('S001','JOE','CSE')";
            String sql3
                = "INSERT INTO STUDENT VALUES('S002','BECK','IT')";
            String sql4
                = "INSERT INTO STUDENT VALUES('S003','KANE','ECE')";
            String sql5
                = "INSERT INTO STUDENT VALUES('S004','FALLON','CSE')";
            String sql6
                = "INSERT INTO STUDENT VALUES('S005','LIAM','CSE')";
 
            // Step 5: Execute the query
            s.addBatch(sql1);
            s.addBatch(sql2);
            s.addBatch(sql3);
            s.addBatch(sql4);
            s.addBatch(sql5);
            s.addBatch(sql6);
 
            // Executing the sql commands
            s.executeBatch();
 
            // Obtaining the resultset
 
            ResultSet rs
                = s.executeQuery("SELECT * FROM STUDENT");
 
            // Retrieving the ResultSetMetadata object
            ResultSetMetaData rsMetaData = rs.getMetaData();
 
            // Retrieving the list of column names
            int count = rsMetaData.getColumnCount();
 
            // Step 6: Process the statements
            for (int i = 1; i <= count; i++) {
                System.out.print(rsMetaData.getColumnName(i)
                                 + "\t");
            }
 
            System.out.println(
                "\n----------------------------------------------------------------");
            while (rs.next()) {
                System.out.println(rs.getString(1) + "\t\t"
                                   + rs.getString(2) + "\t"
                                   + rs.getString(3));
            }
 
            // Step 7: Close the connection
            con.commit();
            con.close();
        }
 
        // Catch block to handle if exception occurs
        catch (Exception e) {
 
            // Print the exception
            System.out.println(e);
        }
    }
}


输出:

示例 2:

Java

// Java Program to Use Methods of Column
// to get column name in JDBC
 
// Step 1: Importing DB files
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Try block to check if exception occurs
        try {
 
            // Step 2: Loading and registering drivers
 
            // Loading driver class
            // using forName() method
            Class.forName("oracle.jdbc.OracleDriver");
 
            // Step 3: Establish a connection
 
            // Create connection object
            Connection con = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe",
                "cse", "cse");
            Statement s = con.createStatement();
 
            // Step 4: Create a starement/s
            // create table
            String sql1
                = "CREATE TABLE STUDENT(STUDENTID VARCHAR2(20) PRIMARY KEY, NAME VARCHAR2(20), DEPARTMENT VARCHAR2(10))";
            // insert records in the table
            String sql2
                = "INSERT INTO STUDENT VALUES('S001','JOE','CSE')";
            String sql3
                = "INSERT INTO STUDENT VALUES('S002','BECK','IT')";
            String sql4
                = "INSERT INTO STUDENT VALUES('S003','KANE','ECE')";
            String sql5
                = "INSERT INTO STUDENT VALUES('S004','FALLON','CSE')";
            String sql6
                = "INSERT INTO STUDENT VALUES('S005','LIAM','CSE')";
 
            // Step 5: Execute the query
            s.addBatch(sql1);
            s.addBatch(sql2);
            s.addBatch(sql3);
            s.addBatch(sql4);
            s.addBatch(sql5);
            s.addBatch(sql6);
 
            // Executing the sql commands
            s.executeBatch();
 
            // Obtaining the resultset
 
            ResultSet rs
                = s.executeQuery("SELECT * FROM STUDENT");
 
            // Retrieving the ResultSetMetadata object
            ResultSetMetaData rsMetaData = rs.getMetaData();
 
            // Retrieving the list of column names
            int count = rsMetaData.getColumnCount();
 
            // Step 6: Process the statements
            for (int i = 1; i <= count; i++) {
                System.out.print(rsMetaData.getColumnName(i)
                                 + "\t");
            }
 
            System.out.println(
                "\n----------------------------------------------------------------");
            while (rs.next()) {
                System.out.println(rs.getString(1) + "\t\t"
                                   + rs.getString(2) + "\t"
                                   + rs.getString(3));
            }
 
            // Step 7: Close the connection
            con.commit();
            con.close();
        }
 
        // Catch block to handle if exception occurs
        catch (Exception e) {
 
            // Print the exception
            System.out.println(e);
        }
    }
}

输出: