我需要按列读取文件,我需要将其存储在数据库中。我的问题是文件内容没有存储在数据库中,而代码只是读取内容。我在存储时遇到错误。
代码:
public class Test3 {
private static String vrms;
private static String irms;
private static String total;
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test3";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,password);
System.out.println("Connection Established");
return conn;
} catch (Exception e) {
System.out.println("Connection not established");
return null;
} }
public static void main(String[] args) throws Exception {
FileInputStream fstream = new FileInputStream("D:/data/database.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
strLine.split(" ");
System.out.println(strLine);
}
in.close();
FileInputStream fis = null;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
File file = new File(strLine);
fis = new FileInputStream(file);
pstmt = conn.prepareStatement("insert into meter1(vrms, irms, total) values (?, ?, ?)");
pstmt.setString(1, vrms);
pstmt.setString(2, irms);
pstmt.setString(3, total);
pstmt.executeUpdate();
conn.commit();
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
fis.close();
conn.close();
}}}
错误: 10 11 0 12 13 0 14 15 0 连接已建立 错误:null 显示java.lang.NullPointerException 在java.io.File。(未知来源) 在vidhya.Test3.main(Test3.java:71) 线程" main"中的例外情况显示java.lang.NullPointerException 在vidhya.Test3.main(Test3.java:85)
答案 0 :(得分:0)
您没有将从文件中读取的信息存储在任何变量(vrms,irms或total)中。在发布此问题之前,请更正您的代码。
发布样本数据文件和列数据类型会很有帮助。
答案 1 :(得分:0)
这是示例代码,可能会有所帮助.. 用正确的db列替换列名。
public static void main(String[] args) throws IOException, SQLException {
PreparedStatement preparedstatement = null;
try{
String read=null;
in = new BufferedReader(new FileReader("patientlist.txt"));
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
name=splited[0];
age=splited[1];
height=splited[2];
weight=splited[3];
addpatient(connection, preparedstatement, name, age, height, weight);
}
}
catch (IOException e) {System.out.println("There was a problem: " + e);}
if (connection != null)
try{connection.close();} catch(SQLException ignore){}
}
public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age, String height, String weight) throws SQLException{
preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
preparedstatement.setString(1, name);
preparedstatement.setString(2, age);
preparedstatement.setString(3, height);
preparedstatement.setString(4, weight);
preparedstatement.executeUpdate();
}