gpt4 book ai didi

java - 使用java中变量传递的名称创建一个模式

转载 作者:行者123 更新时间:2023-12-02 12:23:35 25 4
gpt4 key购买 nike

我正在使用 jdbc 通过 java 中的类在 postgresql 中创建模式。它似乎工作正常,但我需要一个函数来创建模式,我想知道是否可以使用变量传递的名称创建一个模式...这是我的类 CreateSchema:

这可能吗?

String sql = "CREATE SCHEMA centro";

在这一行中“centro”就像一个变量。

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");

System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println("Creating Schema...");
stmt = conn.createStatement();

String sql = "CREATE SCHEMA centro";
stmt.executeUpdate(sql);
System.out.println("Schema created successfully...");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}

谢谢。

最佳答案

首先,您可以连接到 postgresql,而无需将数据库名称获取到 BASE_URL。关于你的问题。是的,您可以通过将 SQL 语句连接到给定名称来创建或删除数据库:"CREATE DATABASE "+ databseName

所以你的代码可能如下:

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");

System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println("Creating Schema...");
stmt = conn.createStatement();

String dbName = "centro"; // or get it from command line
String sql = "CREATE SCHEMA " + dbName;
stmt.executeUpdate(sql);
System.out.println("Schema created successfully...");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}

关于java - 使用java中变量传递的名称创建一个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com