package sqlConn;
import java.io.*;
import java.sql.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception{
List students=new LinkedList();
FileReader fin=new FileReader("res/students.txt");
BufferedReader in=new BufferedReader(fin);
String line=in.readLine();
while(line != null)
{
line = line.trim(); //去除字符串中前後空格
if( line.length() > 0 ) //檢查是否是空行
{
Student student = new Student();
student.parseStudent(line);
students.add(student);
}
line = in.readLine();
}
in.close();
fin.close();
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=student";
String userName="sa"; //默認用戶名
String userPwd="12345"; //密碼
Class.forName(driverName).newInstance();
Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd);
//System.out.println("連接成功!"); //如果連接成功,控制台輸出“連接成功!”
Statement stat = dbConn.createStatement();
Iterator iter = students.iterator();
while(iter.hasNext())
{
Student stu = (Student)(iter.next());
String command = "INSERT INTO stu VALUES('";
command += stu.getID()+"','";
command += stu.getName()+"','";
command += stu.getDepartment()+"')";
System.out.println(command);
stat.executeUpdate(command);
}
}
}
class Student implements Serializable
{
private String sno;
private String sn;
private String dept;
public void parseStudent(String str)
{
int tokenCount;
StringTokenizer t = new StringTokenizer(str);
tokenCount = t.countTokens();
t.nextToken(); //序號
sno = t.nextToken(); //學號
sn = t.nextToken(); //姓名
if( tokenCount > 7 )
dept = t.nextToken();
}
public String toString()
{
String s = sno + " " + sn;
for(int l = s.length();l<21; l++) s +=" "; //對齊
return s + dept;
}
public String getID(){return sno;}
public String getName(){return sn;}
public String getDepartment(){return dept;}
}
你的代碼裡面t.nextToken(); //序號這個去掉。students.txt裡面只有三列,學號,姓名和課程,但是你在解析的時候卻解析成4列,所以錯了。