Java JDBC:更改表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23481131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java JDBC: Altering table
提问by
I wish to make the following alterations to this table:
我希望对此表进行以下更改:
Add: Column for state (varchar(20)) column for date (timestamp)
添加:状态列 (varchar(20)) 日期列(时间戳)
I am unsure how to do so
我不确定该怎么做
String createTable = "Create table aircraft ("
+"aircraftNumber int,"
+"airLineCompany varchar(20),"
+"departureAirport varchar (20),"
+"fuelPercentage int,"
+"passengerCount int);";
回答by Mureinik
You should execute
an alter
statement:
您应该execute
的alter
语句:
Connection conn = ...;
Statement s = conn.createStatement();
s.execute("ALTER TABLE aircraft " +
"ADD COLUMN state VARCHAR(20), " +
"ADD COLUMN `date` TIMESTAMP");
回答by Luiggi Mendoza
To add columns in a database table, you use the ALTER TABLE
statement:
要在数据库表中添加列,请使用以下ALTER TABLE
语句:
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 dateadds 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?.
请注意,我不使用date
作为字段名称的原因有两个:1) 它是大多数数据库引擎中的保留关键字,2) 表字段名称必须易于读者理解,名为date的字段不添加任何值所有到当前模型,哪个日期:创建日期,最后更新日期,飞机到达日期,飞机事故日期?。
Then, in Java, use Statement#execute
to perform any DDL statement in JDBC.
然后,在 Java 中,用于Statement#execute
在 JDBC 中执行任何 DDL 语句。
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();
回答by Hisham Mahmoud
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());
}