问题描述
- 将student.txt文件写入sqlserver数据库,学号写不进去,后面就错位了,求大神
- 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(dbURLuserNameuserPwd);
//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列,所以错了。
解决方案二:
students.txt 中是没有序号的,那是编辑器自动显示在行头的(明显颜色都不一样),下面这句是多余的
t.nextToken(); //序号
时间: 2025-01-30 02:58:05