【问题标题】:MySQL create or alter tableMySQL 创建或更改表
【发布时间】:2014-01-23 00:29:12
【问题描述】:

我正在为我的数据库使用 MySQL 5.1,并通过 Java 程序 (JBDC) 发送命令。 是否有用于创建或更改表的 MySQL 命令? 假设我有一个下表:

+----------+----------+
| column_a | column_b |
+----------+----------+
| value_a  | value_b  |
+----------+----------+

现在我想使用一个命令,如果它不存在,它将添加一个列“column_c”。 这将导致:

+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
| value_a  | value_b  |          |
+----------+----------+----------+

如果表不存在,它将创建一个具有指定列的新表

+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+

最后,如果表中的列没有在命令中指定,它会它们保持不变

【问题讨论】:

  • 据我所知没有ALTER TABLE IF,也许你应该看看像“liquibase”或“flyway”这样的工具
  • 我不认为只需要一个命令就需要使用这些程序,@RC.. 没有其他办法吗?
  • 检查数据库元数据并在需要时创建列
  • 看来这是唯一的方法,@RC.. 会尝试。

标签: java mysql database alter


【解决方案1】:

类似的方法可能是一个解决方案(这需要表中至少有一条记录才能工作):

package com.stackoverflow.so20935793;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class App {

    // complete this:
    private static final String JDBC_URL = ".....";
    private static final String JDBC_USER = ".....";
    private static final String JDBC_PASS = ".....";

    public static void main(final String[] args) {
        Connection con = null;
        PreparedStatement stm = null;
        ResultSet rs = null;

        try {
            con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
            stm = con.prepareStatement("SELECT * FROM your_table LIMIT 1");
            rs = stm.executeQuery();
            if (rs.next() && rs.getMetaData().getColumnCount() == 2) {
                // add your new column
            }
        } catch (final SQLException ex) {
            // handle exception
        } finally {
            closeQuietly(rs);
            closeQuietly(stm);
            closeQuietly(con);
        }
    }

    private static void closeQuietly(final AutoCloseable what) {
        if (what == null) {
            return;
        }

        try {
            what.close();
        } catch (final Exception ex) {
            // ignore
        }
    }
}

(未测试)

【讨论】:

    【解决方案2】:
    /*Making the connection*/
    try {
             //an exception is thrown which will be caught in the catch block
            con = DriverManager.getConnection("jdbc:mysql:exaple.com", "username", "pass");
    
            //create a statement object
            stmt = con.createStatement();
            //supply the statement object with a string to execute                          
            stmt.executeUpdate("ALTER TABLE table_name ADD column_name datatype");
    
            //close the statement and connection
            stmt.close();
            con.close();
    
        } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
    

    我认为这对你有用。

    【讨论】:

    • 我想你错过了这个问题,我要求在 MySQL 中使用命令,而不是 Java 连接。 是否有创建或更改表的命令?
    • 是的,命令是 executeUpdate。 ALTER TABLE table_name ADD column_name datatype 我希望这对你有用
    • 问题是,如果表不存在,它就不会创建它。此外,您的示例中无法检测缺失的列。
    【解决方案3】:

    这是用 Java 编写的用于创建名为 Coffees 的表的代码:

    /*Making the connection*/
    try {//if any statements within the try block cause problems, rather than the program failing
             //an exception is thrown which will be caught in the catch block
            con = DriverManager.getConnection(url, "your username", "your password");
    
            //create a statement object
            stmt = con.createStatement();
            //supply the statement object with a string to execute                          
            stmt.executeUpdate("create table COFFEES (COF_NAME varchar(32), " +
                                "SUP_ID int, PRICE double, SALES int, TOTAL int, " +
                                "primary key(COF_NAME))");
    
            //close the statement and connection
            stmt.close();
            con.close();
    
        } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
    

    说明: -在这个例子中,java程序与位于服务器上的数据库进行交互,所以我们必须首先设置服务器所在的url并登录用户名和密码,你可能没有使用相同的方法我用了。 -这些需要在你的java程序的顶部声明:

    String url = "jdbc:mysql://www.yoururlexample.co.uk"; 
    Connection con;    
    Statement stmt
    

    希望这会有所帮助,您将能够将数据插入数据库并执行查询。

    编辑:

    如果您想在不存在名为“COFFEES”的表时创建一个表,则可以在 executeUpdate 语句中使用它:

    create table if not exists COFFEES
    

    【讨论】:

    • 我想你错过了这个问题,我要求在 MySQL 中使用命令,而不是 Java 连接。 是否有创建或更改表的命令?
    • 嗯我不完全确定,但不应该添加这些来做你想做的事吗?:stmt.executeUpdate(CREATE TABLE IF NOT EXISTS .....); stmt.executeUpdate(ALTER TABLE .....);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2021-12-30
    • 2021-11-06
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多