在Java编程中,如何编辑(添加或更新)表的列以及如何删除表?
以下示例使用SQL命令:create
,alter
和drop
命令来创建,编辑或删除表。
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