我使用Toad數據庫建模器創建了Oracle方案。我通常使用SQL開發人員用SQL語句導入新方案。現在我想創建一個Java程序來自動完成這個過程。我創建至今這將打開連接到Oracle這樣的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程序,我可以用於相同的目的?
你可以看看http://www.coderanch.com/t/298527/JDBC/databases/execution-PL-SQL-JDBC,但它取決於PL/SQL文件的結構。 – BigMike 2013-02-19 14:05:31
Ant? Maven的?哈德森? – APC 2013-02-19 14:05:43
@APC我使用Maven。 – 2013-02-19 14:06:28