有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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) 个答案

  1. # 1 楼答案

    循环部分

    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列,我使用的是假设每列的间距为1。要从字符串转换日期和时间,你可以在谷歌上搜索