Reputation:
I wish to make the following alterations to this table:
Add: Column for state (varchar(20)) column for date (timestamp)
I am unsure how to do so
String createTable = "Create table aircraft ("
+"aircraftNumber int,"
+"airLineCompany varchar(20),"
+"departureAirport varchar (20),"
+"fuelPercentage int,"
+"passengerCount int);";
Upvotes: 5
Views: 18976
Reputation: 11
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());
}
Upvotes: 1
Reputation: 85779
To add columns in a database table, you use the ALTER TABLE
statement:
ALTER TABLE aircraft
ADD COLUMN state VARCHAR(20),
ADD COLUMN dateCreated DATETIME
Note that I don't use date
as name for your field for two reasons: 1) It is a reserved keyword in most database engines, 2) A table field name must be easy to understand for readers, A field named date adds no value at all to the current model, which date: date of creation, date of last update, date of aircraft arrival, date of aircraft accident?.
Then, in Java, use Statement#execute
to perform any DDL statement in JDBC.
To sum it up:
String sql = "ALTER TABLE aircraft "
+ "ADD COLUMN state VARCHAR(20), "
+ "ADD COLUMN dateCreated DATETIME";
Connection con = ...
Statement stmt = con.createStatement(sql);
stmt.execute();
Upvotes: 3
Reputation: 311853
You should execute
an alter
statement:
Connection conn = ...;
Statement s = conn.createStatement();
s.execute("ALTER TABLE aircraft " +
"ADD COLUMN state VARCHAR(20), " +
"ADD COLUMN `date` TIMESTAMP");
Upvotes: 3