java中文件读取文件操作数据库 给个例子 谢谢
连接数据库:
public class DBConnect {
public Connection getConnect(String driver, String url, String user, String pwd) {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void closeConnect(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
SqlExecutor类:
public class SqlExecutor {
private Connection conn;
private Statement stmt;
private DBConnect db = new DBConnect();
public int[] exeBatch(String driver, String url, String user, String pwd, String[] sqls) {
int[] result = new int[sqls.length];
conn = db.getConnect(driver, url, user, pwd);
try {
stmt = conn.createStatement();
for (int i = 0; i < sqls.length; i++) {
if (sqls[i].endsWith(";"))
stmt.addBatch(sqls[i]);
}
result = stmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
db.closeConnect(conn);
}
return result;
}
}
读取方法
public String readFile(String filePath) {
String doc = null;
File file = new File(filePath);
if (file == null) {
return null;
}
try {
// 用文件输入流构建输入流
InputStream is = new BufferedInputStream(new FileInputStream(file));
BufferedReader bReader = new BufferedReader(new InputStreamReader(
is, "utf-8"));
StringBuilder sb = new StringBuilder();
String rLine = null;
while ((rLine = bReader.readLine()) != null) {
String tmp_rLine = rLine;
int str_len = tmp_rLine.length();
if (str_len > 0) {
sb.append(tmp_rLine + " ");
}
tmp_rLine = null;
}
doc = sb.toString();
bReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
测试类:
public class Test {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FileUtil util = new FileUtil();
String sqlPath = "g:/db.sql";
String[] sqls = util.readSqlFile(sqlPath);
for (String s : sqls) {
System.out.println(s);
}
// 数据库生成测试
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.37.111:3306/mysql?useunicode=true&characterEncoding=utf-8";
String username = "root";
String pwd = "ipanel";
SqlExecutor creator = new SqlExecutor();
System.out.println(creator.exeBatch(driver, url, username, pwd, sqls));
}
}