- 论坛徽章:
- 0
|
回复 4# nan_jia ,
啊啊
感谢这位好心大大啊!!我现在已经实现了的功能是用命令行参数读入一个配置文件去连接数据库,然后在读一个文件将该文件的内容存入数据库已有的表里。可是我们老师要求的是读五个文件,然后将这五个文件分别存入不同的已存在的表里面?请问我存入数据那块的代码就要重复写五遍吗? 下面是我全部代码- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.util.List;
- import java.util.ArrayList;
- import java.io.*;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.PreparedStatement;
- public class db {
- public static void main(String[]args){
- /*read the properties*/
- String s;
- int t = 0;
- String[] sa=new String[5];
- List data = new ArrayList();
- try{
- BufferedReader in =new BufferedReader(new FileReader(args[0]));
- while((s=in.readLine())!=null){
- sa[t] =s.substring(0);
- t++;
- }
- }
- catch(FileNotFoundException e){
- e.printStackTrace();
- }
- catch(IOException e){
- e.printStackTrace();
- }
- /*connect the DB*/
- String url = "jdbc:mysql://"+sa[0]+":"+sa[1]+"/"+sa[2];
- String username = sa[3];
- String password = sa[4];
- Connection conn = null;
- PreparedStatement stmt = null;
- try{
- conn = DriverManager.getConnection(url, username, password);
-
- }catch (SQLException e1) {
- e1.printStackTrace();
- }
- /*put data in DB*/
- File file = new File(args[1]);
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(file);
- InputStreamReader input = new InputStreamReader(fis);
- BufferedReader br = new BufferedReader(input);
- String line = null;
- String sql = null;
- String info[] = null;
- String path = file.getAbsolutePath();//得到选择文件的全路径
- String fileName = path.substring(path.lastIndexOf("\\")+1, path.lastIndexOf("."));//取得所选文件名
- String province = fileName.substring(0,fileName.length()-2);
- String cardType = fileName.substring(fileName.length()-2);
- try {
- while((line = br.readLine())!= null){
- info = line.split(",");
- sql = "insert into cc(A,B,C)values('"+ info[0] +"','"+info[1]+"','"+info[2]+"')";
- stmt = conn.prepareStatement(sql);
- stmt.executeUpdate();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
-
- }catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- if(conn != null){
- try {
- conn.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
- }
-
- }
复制代码 |
|