Java JDBC:改变表

时间:2014-05-05 20:22:10

标签: java mysql sql jdbc ddl

我希望对此表做出以下修改:

添加:状态列(varchar(20))      日期列(时间戳)

我不确定该怎么做

String createTable = "Create table aircraft ("
                        +"aircraftNumber int,"
                        +"airLineCompany varchar(20),"
                        +"departureAirport varchar (20),"
                        +"fuelPercentage int,"
                        +"passengerCount int);";

3 个答案:

答案 0 :(得分:2)

要在数据库表中添加列,请使用ALTER TABLE语句:

ALTER TABLE aircraft
    ADD COLUMN state VARCHAR(20), 
    ADD COLUMN dateCreated DATETIME

请注意,我没有使用date作为您的字段的名称,原因有两个:1)它是大多数数据库引擎中的保留关键字,2)表字段名称必须简单要了解读者,名为 date 的字段根本不会为当前模型添加任何值,该日期:创建日期,上次更新日期,飞机到达日期,飞机事故发生日期?< /子>


然后,在Java中,使用Statement#execute在JDBC中执行任何DDL语句。

总结一下:

String sql = "ALTER TABLE aircraft "
    + "ADD COLUMN state VARCHAR(20), "
    + "ADD COLUMN dateCreated DATETIME";
Connection con = ...
Statement stmt = con.createStatement(sql);
stmt.execute();

答案 1 :(得分:1)

您应该execute alter声明:

Connection conn = ...;
Statement s = conn.createStatement();
s.execute("ALTER TABLE aircraft " + 
          "ADD COLUMN state VARCHAR(20), " + 
          "ADD COLUMN `date` TIMESTAMP");

答案 2 :(得分:0)

Connection conn=new Connection("database path");
String sql="ALTER TABLE Table_name ADD COLUMN Column_name Datatype";

try{
    conn.ExecuteNonSelect(sql);
}
catch(Exception e)
{
    JOptionPane.showMessageDialog(null, e.getMessage());
}