我使用 Toad 数据库建模器创建了 Oracle 方案。我通常使用 SQL developer 来导入带有 SQL 语句的新方案。现在我想创建自动化这个过程的 Java 程序。到目前为止,我创建了这个 Java 代码,它打开了与 Oracle 的连接:
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程序可以用于相同的目的吗?