如何以列方式读取数据并将保存在mysqldb中作为列

时间:2017-06-02 05:27:03

标签: java mysql jdbc

大家好我试图从包含数据的文本文件中读取数据,如c1,c2,c3等我必须从文本文件中读取这些列,我必须将这些列保存在MySQL数据库中,如c1,c2, c3列但c1列数据类型为int,c1列数据类型为date,c1列为数据类型时间。

class ReadFile 
{
    public String[] readLines(String filename) throws IOException 
    {
        FileReader fileReader = new FileReader(filename);

        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) 
        {
            lines.add(line);
        }

        bufferedReader.close();

        return lines.toArray(new String[lines.size()]);
    }   
}


public class Test {
    public static void main(String[] args) {
        ReadFile rf = new ReadFile();

        // The text file location of your choice
        String filename = "D://downloads//1_attlog.txt";

        try
        {
            String[] lines = rf.readLines(filename);

            for (String line : lines) 
            {
                System.out.println(line);
            }
        }
        catch(IOException e)
        {
            // Print out the exception that occurred
            System.out.println("Unable to create "+filename+": "+e.getMessage());              
        }
    }
}

测试JDBC

public class TestJDBC {
    public static Connection getConnection() throws Exception {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/kallayyaDB";
        String username = "root";
        String password = "root";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
      }


      public static void main(String[] args) throws Exception {


        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
          conn = getConnection();
          String query = "insert into testTable(deptnum, deptname, deptloc) values(?, ?, ?)";

          pstmt = conn.prepareStatement(query); // create a statement
          pstmt.setInt(1, 1); // set input parameter 1
          pstmt.setString(2, "deptname"); // set input parameter 2
          pstmt.setString(3, "deptLocation"); // set input parameter 3
          pstmt.executeUpdate(); // execute insert statement
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          pstmt.close();
          conn.close();
        }
      }
}

1 个答案:

答案 0 :(得分:0)

在循环部分

for (String line : lines) 
{
   StringTokenizer st2 = new StringTokenizer(line, "\t");
   String c[]=new String[3];
   int i=0;    
   while (st2.hasMoreElements()) 
   {
     c[i]=String.valueOf(st2.nextElement());
     i++;
   }
}

现在您可以使用c [0],c [1],c [2]准备查询,大小为3,因为您提到的只有3列nd \ ti使用假设每列有1个标签的间隙。对于从字符串转换的日期和时间,您可以谷歌。