Java如何編輯(新增或更新)表的列以及如何刪除表?

2019-10-16 22:25:57

在Java程式設計中,如何編輯(新增或更新)表的列以及如何刪除表?

以下範例使用SQL命令:createalterdrop命令來建立,編輯或刪除表。

package com.yiibai;

import java.sql.*;

public class EditTable {
    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";
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found " + e);
        }
        Connection con = DriverManager.getConnection(DB_URL, User, Passwd);
        Statement stmt = con.createStatement();
        String query = "CREATE TABLE employees2(id INTEGER PRIMARY KEY, first_name CHAR(50), last_name CHAR(75))";

        stmt.execute(query);
        System.out.println("Employee2 table created");
        String query1 = "aLTER TABLE employees2 ADD address CHAR(100) ";
        String query2 = "ALTER TABLE employees2 DROP COLUMN last_name";

        stmt.execute(query1);
        stmt.execute(query2);
        System.out.println("Address column added to the table & last_name column removed from the table");

        String query3 = "drop table employees2";
        stmt.execute(query3);
        System.out.println("Employees table removed");
    }
}

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

Employee2 table created
Address column added to the table & last_name column removed from the table
Employees table removed

註:如果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