数据库驱动

来源:互联网 发布:java if else 简写 编辑:程序博客网 时间:2024/06/06 04:19
package newexam;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DAOAccess {private Connection con = null;private String fileName;private boolean isCrp = false;public DAOAccess(String fileName) {this.fileName = fileName;if (fileName.endsWith(".crp")) {isCrp = true;File srcFile = new File(fileName);File tempFile = null;try {tempFile = File.createTempFile("tiku", ".mdb");BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFile));BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));int ch;while ((ch = in.read()) != -1) {ch ^= 9;out.write(ch);}in.close();out.close();this.fileName = tempFile.getAbsolutePath();} catch (FileNotFoundException e) {System.out.println("找不到文件!");e.printStackTrace();} catch (IOException e) {System.out.println("文件操作失败!");e.printStackTrace();}}}public Connection getConnection() {try {Class.forName("com.hxtt.sql.access.AccessDriver");String url = "jdbc:access:///" + fileName;con = DriverManager.getConnection(url);} catch (ClassNotFoundException e) {System.out.println("ACCESS_JDBC加载失败");e.printStackTrace();} catch (SQLException e) {System.out.println("数据库连接或创建语句失败");e.printStackTrace();}return con;}public void close() {if (con != null)try {con.close();} catch (SQLException e) {System.out.println("数据库无法关闭");e.printStackTrace();}if (isCrp) {System.out.println("删除临时文件:" + this.fileName);File file = new File(this.fileName);if (file.exists()) {file.deleteOnExit();}}}}

原创粉丝点击