一共有三个类:WriteFile ; ReadFile ; InsertDB ;
//WriteFile.java //用于将信息写入文本文件 package org.mb.insertfromfile; import java.io.*; public class WriteFile{ private int count = 0 ; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void write() throws Exception{ File f = new File("f:\\stu1.dat"); f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); DataOutputStream dos = new DataOutputStream(fos); this.count++; dos.writeUTF("洪吉童"); dos.writeInt(80); dos.writeInt(75); dos.writeInt(65); dos.writeInt(50); this.count++; dos.writeUTF("徐光豪"); dos.writeInt(90); dos.writeInt(100); dos.writeInt(100); dos.writeInt(100); this.count++; dos.writeUTF("林顺喜"); dos.writeInt(60); dos.writeInt(70); dos.writeInt(55); dos.writeInt(75); this.count++; dos.writeUTF("李之梅"); dos.writeInt(60); dos.writeInt(80); dos.writeInt(75); dos.writeInt(80); this.count++; dos.writeUTF("洪顺熙"); dos.writeInt(80); dos.writeInt(70); dos.writeInt(90); dos.writeInt(85); this.count++; dos.writeUTF("朴顺吉"); dos.writeInt(100); dos.writeInt(80); dos.writeInt(90); dos.writeInt(85); dos.flush(); dos.close(); } }
//ReadFile.java //用于返回文本中的信息 package org.mb.insertfromfile; import java.io.*; public class ReadFile { public String[] read()throws Exception{ WriteFile wr = new WriteFile(); wr.write(); String str[] = new String[wr.getCount()]; File f = new File("F:\\stu.dat"); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); for (int i=0 ; i<str.length ; i++){ str[i] = "'"+dis.readUTF()+"'"+","+dis.readInt()+","+dis.readInt()+","+dis.readInt()+","+dis.readInt(); System.out.println(str[i]) ; } return str ; } }
//InsertDB.java //把ReadFile返回的信息更新到MySql数据库 package org.mb.insertfromfile; import java.sql.*; public class InsertDB { public static final String DBDRIVER="org.gjt.mm.mysql.Driver"; public static final String DBURL="jdbc:mysql://localhost:3306/test"; public static final String DBUSER="root"; public static final String DBPASSWORD="mabin870906"; public static void main(String[] args) throws Exception{ Connection conn = null ; Class.forName(DBDRIVER); conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD); Statement stmt = conn.createStatement(); String temp[] = new ReadFile().read(); for (int i=0 ; i<temp.length ; i++){ String sql = "INSERT INTO score(name,chinese,english,math,scintist) VALUE("+temp[i]+")"; stmt.executeUpdate(sql); } stmt.close(); conn.close(); } }
Copyright @ 2024 Jesuca Powered by .NET 9.0 on Kubernetes Powered by: .Text and ASP.NET Theme by: .NET Monster