gpt4 book ai didi

java - 使用Java程序创建Oracle模式

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

我使用 Toad 数据库建模器创建了 Oracle 方案。我通常使用SQL Developer通过SQL语句导入新方案。现在我想创建一个 Java 程序来自动化这个过程。到目前为止,我创建了这个打开与 Oracle 的连接的 Java 代码:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;
import org.junit.BeforeClass;
import org.junit.Test;

public class OracleCreateScheme
{

public OracleCreateScheme()
{
}

@BeforeClass
public static void setUpClass() throws Exception
{
// rcarver - setup the jndi context and the datasource
try
{
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES,
"org.apache.naming");
InitialContext ic = new InitialContext();

ic.createSubcontext("java:");
ic.createSubcontext("java:/comp");
ic.createSubcontext("java:/comp/env");
ic.createSubcontext("java:/comp/env/jdbc");

// Construct DataSource
OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
ds.setURL("jdbc:oracle:thin:@host:port:db");
ds.setUser("admin");
ds.setPassword("qwerty");

ic.bind("java:/comp/env/jdbc/oracle", ds);
}
catch (NamingException ex)
{
//Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex);
}

}

@Test
public void createOracleScheme() throws SQLException, NamingException
{

Context initContext = new InitialContext();
Context webContext = (Context) initContext.lookup("java:/comp/env");

DataSource ds = (DataSource) webContext.lookup("jdbc/Oracle");

String SqlStatement = null;

if (ds == null)
{
throw new SQLException();
}


Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}

PreparedStatement ps = null;
ResultSet resultSet = null;

try
{
conn.setAutoCommit(false);
boolean committed = false;
try
{

ps = conn.prepareStatement(SqlStatement);
resultSet = ps.executeQuery();

conn.commit();
committed = true;
}
finally
{
if (!committed)
{
conn.rollback();
}
}
}
finally
{
ps.close();
conn.close();
}

}
}

您能告诉我如何修改代码才能将 SQL 文件执行到 Oracle 中吗?还有没有现成的 Java 程序可以用于相同目的?

最佳答案

我建议使用现有的东西,而不是编写自己的实现。有许多强大的工具可以完成此任务:

Maven SQL 插件 [mojo.codehaus.org/sql-maven-plugin/examples/execute.html]

DBUnit 文件加载器 [www.dbunit.org/howto.html#fileloader]

或者Spring(如果你被迫使用它:-)) [static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html]

查看这篇文章: [stackoverflow.com/questions/7565420/create-and-clean-db-setup-only-once-for-testing-all-daos]

希望这有帮助......

关于java - 使用Java程序创建Oracle模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14959335/

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