繁体   English   中英

类型不匹配:无法从元素类型对象转换为字符串

[英]Type mismatch: cannot convert from element type Object to String

有人可以看看这一点,并告诉我为什么我得到这个错误。 我试图从Mysql数据库中提取表并将其打印到文本文件。 我给我上面列出的错误。

package db;

import java.io.*;
import java.sql.*;
import java.util.*;

public class TableToTextFile {
    public static void main(String[] args) {
        List<int[]> data = new ArrayList();

        try {
            Connection con = null;
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "root");
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("Select * from employee");

            while (rs.next()) {
                String id = rs.getString("emp_id");
                String name = rs.getString("emp_name");
                String address = rs.getString("emp_address");
                String contactNo = rs.getString("contactNo");
                data.add(id + " " + name + " " + address + " " + contactNo);

            }
            writeToFile(data, "Employee.txt");
            rs.close();
            st.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static void writeToFile(java.util.List list, String path) {
        BufferedWriter out = null;
        try {
            File file = new File(path);
            out = new BufferedWriter(new FileWriter(file, true));
            for (String s : list) {
                out.write(s);
                out.newLine();

            }
            out.close();
        } catch (IOException e) {
        }
    }
}

可能是因为您的列表已被声明为接受整数数组,并且您正在传递字符串。

List<int[]> data = new ArrayList();

更改它以接受字符串。

List<String> data = new ArrayList<>();

一个更好,更面向对象的设计将是创建一个名为Employee的类并改为使用它。

public class Employee {
    private String id;
    private String name;
    ...
}

List<Employee> data = new ArrayList<>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM