作者原创,转载注明出处:
代码:
package importfile; import java.io.*; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class test { public static void main(String[] args) throws Exception { SqlExport exprot = new SqlExport(); if(exprot.isExist()) { System.out.println("脚本文件创建成功"); }else { System.out.println("脚本文件创建失败"); return; } List<String> lists = new ArrayList<String>(); lists.add("sql语句"); exprot.export(lists); // String url="jdbc:oracle:thin:@localhost:1522:orcl11g"; // String user="username"; // String password="password"; // Class.forName("oracle.jdbc.driver.OracleDriver"); // Connection conn = null; // conn = DriverManager.getConnection(url, user, password); // // // PreparedStatement pst = null; // List<String> lists = new ArrayList<String>(); // try { // // pst = conn.prepareStatement("select * from test"); // ResultSetMetaData rsd = pst.executeQuery().getMetaData(); // for(int i = 0; i < rsd.getColumnCount(); i++) { // System.out.print("java类型:"+rsd.getColumnClassName(i + 1)); // System.out.print(" 数据库类型:"+rsd.getColumnTypeName(i + 1)); // lists.add(rsd.getColumnName(i + 1)); // System.out.print(" 字段名称:"+rsd.getColumnName(i + 1)); // System.out.print(" 字段长度:"+rsd.getColumnDisplaySize(i + 1)); // System.out.println(); // } // for(int i = 0;i<lists.size();i++) // { // System.out.println(lists.get(i)); // } // // // } catch(SQLException e) { // throw new RuntimeException(e); // } finally { // try { // pst.close(); // pst = null; // exprot.close(exprot.getOut()); // } catch(SQLException e) { // throw new RuntimeException(e); // } // } // // } } } class SqlExport { public void export (List<String> list) throws IOException { try { for(int i =0;i<list.size();i++) { out.write(list.get(i)+" "); } out.write(" "); out.flush(); } catch (IOException e) { e.printStackTrace(); } } //判断文件是否存在 public boolean isExist() { File file=new File(path); file.delete(); try { out = new FileWriter(path,true); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } public void close(FileWriter out) throws IOException { out.close(); } public FileWriter getOut() { return out; } private List<String> lists; private String path = ".//sql脚本.sql"; private FileWriter out = null; }
注: 其中注释部分是数据连接语句,输出到脚本的sql语句可以在注释部分去组装,