Java读取sql文件并插入MySQL数据库

您所在的位置:网站首页 读取sql文件 Java读取sql文件并插入MySQL数据库

Java读取sql文件并插入MySQL数据库

2024-03-21 13:16| 来源: 网络整理| 查看: 265

.sql 文件里面存的数据格式如下:

INSERT INTO tbl_name (col1, col2, …) VALUES (val1, val2,….), (val3, val4,….)

从别的地方获取到sql文件,将数据插入到你想要的数据库里面,

方法一:

直接在数据库下运行.sql文件:

mysql> source /User/ziqiii/myInsert.sql

 

方法二:

但一般在公司,获取到的.sql文件后,没法直接连数据库插入,需要用代码解决:

 

首先连接MySQL数据库:

(里面有个查询示例,main函数可以改成放在其他函数)

public class Test { // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL // static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&characterEncoding=utf-8"; // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; // 数据库的用户名与密码,需要根据自己的设置 static final String USER = "root"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 System.out.println(" 实例化Statement对象..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, a, b FROM table where id < 10"; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 int id = rs.getInt("id"); String a = rs.getString("a"); String b = rs.getString("b"); System.out.println("ResultSet: " + rs); // 输出数据 System.out.print("ID: " + id); System.out.print(", a: " + a); System.out.print(", b: " + b); System.out.print("\n"); } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 确认关闭资源 try{ if(stmt!=null && !stmt.isClosed()) stmt.close(); if(conn!=null && !conn.isClosed()) conn.close(); System.out.println("Goodbye!"); }catch(SQLException se){ se.printStackTrace(); } } }

 

下面用Spring-web的模块,使用@RestController,用get请求触发函数

(anyway,写在main函数里面也行,随你。看具体实现就行)

@GetMapping("readSQL") public void readSQL() { try { //原生JDBC开发,获取连接 Connection conn = getConnection(); String path = "/Users/ziqiiii/Desktop/testFile/00001.sql"; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); String line = reader.readLine(); Statement stm = conn.createStatement(); String lineValue = null; String sql = null; while ((lineValue = reader.readLine()) != null) { sql = line+lineValue; sql = sql.substring(0,sql.length()-1); System.out.println("-----------------------"); System.out.println(sql); System.out.println("-----------------------"); } reader.close(); } catch (Exception e) { e.printStackTrace(); } }

 

这里采用处理格式是因为,我的sql文件在存放的具体格式是

INSERT INTO tbl_name VALUES (val1, val2,….), (val3, val4,….), (val5, val6,….), ... ... (val7, val8,….);

其他的可以按照具体sql文件格式处理。

 

参考:

Java MySQL 连接



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3