简体   繁体   English

如何将 IF NOT EXISTS 语句用于 ALTER TABLE 语句?

[英]How to use the IF NOT EXISTS Statement for the ALTER TABLE Statement?

I am working on an application wich is written in Java.我正在开发一个用 Java 编写的应用程序。 Now I have to create a new column in my Database.现在我必须在我的数据库中创建一个新列。 But the column shall just be created when it is not existing.但是当它不存在时,应该只创建该列。

So I want to use IF NOT EXISTS and ALTER TABLE to create my new Column.所以我想使用IF NOT EXISTSALTER TABLE来创建我的新列。

Here is what I tried:这是我尝试过的:

//Some import statements and previous, not for the question relevant code

//relevant code:

 Statement alter = conn.createStatement();{
   String alterStr="alter table test_cm_documents ADD if not exists test_id int";
   alter.executeQuery(alterStr);
   System.out.println("Column has been generated.")
 }

Actually I just expected that it prints out "Column has been generated."实际上我只是期望它打印出“列已生成”。 but it gives me the following error Message:但它给了我以下错误消息:

ERROR 1064(42000): You have an error in your SQL syntax;错误 1064(42000):您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if not exists test_id' at line 1检查与您的 MySQL 服务器版本相对应的手册,以获得在第 1 行的“如果不存在 test_id”附近使用的正确语法

I am quite new to the topic so please excuse any mistakes.我对这个话题很陌生,所以请原谅任何错误。 (: (:

You can use:您可以使用:

select * from information_schema.columns
where
table_schame='<enter_your_database_name_here_remove_brackets>' and
table_name='test_cm_documents' and
column_name='test_id'

to recieve list of tuples in your Java application and if the size of this list is 0, execute mysql query:要在您的 Java 应用程序中接收元组列表,如果此列表的大小为 0,请执行 mysql 查询:

alter table test_cm_documents add column test_id int;

Also, you will need to the grant access(for information_schema) to the user specified in your java application.此外,您需要向 java 应用程序中指定的用户授予访问权限(用于 information_schema)。 (Ignore this if user is 'ROOT'). (如果用户是“ROOT”,则忽略此)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM