package com.zzk.cn; import java.io.*; import java.sql.*; import java.util.*; public class TxtToMysql { /** * @param args * 本程序涉及文件IO,字符串分隔StringTokenizer,JDBC,数据库sql语句 */ public static void main(String[] args) { Connection con = null; PreparedStatement pstm = null; FileReader fr = null; BufferedReader br = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://10.1.101.223:3306/weather", "appuser", "opzoon123!"); pstm = con .prepareStatement("insert into student (id,name,age,sex,score) values(?,?,?,?,?)"); fr = new FileReader("D://student.txt"); br = new BufferedReader(fr); for (int i = 0; i < 5; i++) { String s = br.readLine(); StringTokenizer st = new StringTokenizer(s); int ID = Integer.parseInt(st.nextToken()); String name = st.nextToken(); int age = Integer.parseInt(st.nextToken()); String gendar = st.nextToken(); int score = Integer.parseInt(st.nextToken()); pstm.setInt(1, ID); pstm.setString(2, name); pstm.setInt(3, age); pstm.setString(4, gendar); pstm.setInt(5, score); pstm.executeUpdate(); } br.close(); pstm.close(); con.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
注意:将student.txt文件内容建成如下形式:
1 张三 20 male 80
2 lisi 24 female 86
3 wangwu 25 male 93
4 liuliu 36 female 89
5 zhaoqi 29 male 81
改编此代码,在我的天气预报里;
package com.zzk.cn; import java.io.*; import java.sql.*; import java.util.*; public class TxtToMysql { /** * @param args * 本程序涉及文件IO,字符串分隔StringTokenizer,JDBC,数据库sql语句 */ public static void main(String[] args)throws NullPointerException { Connection con = null; PreparedStatement pstm = null; FileReader fr = null; BufferedReader br = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://10.1.101.223:3306/weather", "appuser", "opzoon123!"); pstm = con .prepareStatement("insert into city_info (city_id,city_name) values(?,?)"); fr = new FileReader("D://weather.txt"); br = new BufferedReader(fr); String line = ""; while(null != (line = br.readLine())) { StringTokenizer st = new StringTokenizer(line); int ID = Integer.parseInt(st.nextToken()); String name = st.nextToken(); pstm.setInt(1, ID); pstm.setString(2, name); pstm.executeUpdate(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { pstm.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
时间: 2024-09-27 23:30:36