我有我写的这个程序,但我遇到了问题。我只使用“插入”开始了这个项目,没有“重复键”,它工作得很好。现在自从我添加它以来,代码进入一个循环并且不执行任何东西。我从文件中读取此代码并插入数据库。我尝试了更新,但如果该文件中有新项目,它就不起作用。谁能告诉我我做错了什么。
这是我的代码
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");
}
}