回覆列表
  • 1 # 兔子講Java

    不知道你記事本中的資料的格式具體是什麼樣的?這邊我按我猜測的兩種格式給你舉個例子。

    格式一

    格式二

    公用方法

    獲取連線的方法如下,還有兩個就是關閉連線的方法就不貼圖了。

    表結構

    總結

    import java.io.*;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class TestStudent { public static void insertOne() { Connection conn = getConn(); PreparedStatement pstmt = null; String filePath1 = "C:/Users/Edianzu/Desktop/cc/111.txt";int count = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath1), "gbk"));String sql; while ((sql = br.readLine()) != null) { pstmt = conn.prepareStatement(sql);pstmt.executeUpdate(); count++;} System.out.println("一共成功插入了" + count + "條資料"); } catch (Exception e) { e.printStackTrace(); } closePreparedStatement(pstmt); closeConn(conn); } public static void insertTwo() { Connection conn = getConn(); PreparedStatement pstmt = null; String filePath2 = "C:/Users/Edianzu/Desktop/cc/222.txt"; int count = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath2), "gbk"));String text; String sql = "insert into t_student(id,name) values(?,?)"; pstmt = conn.prepareStatement(sql); while ((text = br.readLine()) != null) {String[] textArr = text.split(",");pstmt.setInt(1, Integer.parseInt(textArr[0]));pstmt.setString(2, textArr[1]);pstmt.executeUpdate();count++; } System.out.println("一共成功插入了" + count + "條資料"); } catch (Exception e) {e.printStackTrace(); } closePreparedStatement(pstmt);closeConn(conn); } public static void main(String[] args) { // 格式一 insertOne(); // 格式二 // insertTwo(); } private static Connection getConn() { String driver = "com.mysql.cj.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=gbk&useSSL=false"; String username = "root"; String password = "admin";Connection conn = null; try { Class.forName(driver);conn = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } private static void closePreparedStatement(PreparedStatement ps) { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } private static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }}

  • 中秋節和大豐收的關聯?
  • 什麼是小蘇打溫泉?