我有这个程序,我写了,我遇到了问题。我使用“插入”开始这个项目只有没有“重复键”,它工作正常。现在,因为我添加了它,代码进入循环并且不执行任何操作。我从文件中读取此代码并插入数据库。我尝试过更新,但如果该文件中有新项目则无效。任何人都可以告诉我我做错了什么。
这是我的代码
import java.sql.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class mysql {
static Connection conn;
public static void main (String argv[]) throws SQLException, ClassNotFoundException {
File file = new File("/home/bandoc/data.txt");
if (!file.exists()) {
System.out.println("Cannot Read File\n");
}
BufferedReader br = null;
//connect to mysql db
Class.forName ("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost/membership? user=My-Username&password=my-Password");
Statement stmt = conn.createStatement();
ResultSet mysqldata = stmt.executeQuery ("select * from logIn");
try {
br = new BufferedReader(new FileReader(file.getPath()));
}catch(IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = "";
try {
line = br.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
PreparedStatement stm = conn.prepareStatement("insert into logIn (logId, logFname, logLname, logDept, logUser, logEmail, logDeptCode) values (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE test =1");
while (line != null) {
if (line.equalsIgnoreCase("ID:")) {
try {
line = br.readLine();
stm.setInt(1,Integer.parseInt(line.toString()));
line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
}
if (line.equalsIgnoreCase( "First:")) {
try {
line = br.readLine();
stm.setString(2,line);
line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
}
if (line.equalsIgnoreCase("Last:")) {
try {
line = br.readLine();
stm.setString(3,line);
line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
}
if (line.equalsIgnoreCase("Dept:")) {
try {
line = br.readLine();
stm.setString(4,line);
line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
if (line.equalsIgnoreCase( "User:")) {
try {
line = br.readLine();
stm.setString(5,line);
line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
}
if (line.equalsIgnoreCase( "Email:")) {
try {
line = br.readLine();
stm.setString(6,line);
line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
}
if (line.equalsIgnoreCase( "Deptcode:")) {
try {
line = br.readLine();
stm.setString(7,line);
//line = br.readLine();
}catch (IOException e) {
e.printStackTrace();
}
}
}
stm.execute();
}
try {
br.close();
}catch(IOException e) {
e.printStackTrace();
}
System.out.println("done");
}
}
答案 0 :(得分:0)
我的猜测是你永远不会离开你的while循环。您读取第一行然后进入一个循环,当读入的行是null
时停止。循环中有一堆条件来检查行,如果匹配某些条件,则读取另一行。因此,如果读取的第一行不是null
,并且第一行在循环中没有匹配条件,那么您将永远陷入该循环。稍微调试就会证明(或反驳这一点),最底层的最终else
条件可能会记录您遇到意外行(并打印出来),然后继续阅读下一行。
答案 1 :(得分:0)
如果您的“行”不符合其中一个条件,例如'ID:',然后下一个readline没有完成,'line'保持不变,因此是一个永无止境的循环