JAVA 执行MYSQL脚本(替换数据库名称)

createDB.sql


SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`@@@dbName@@@` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `@@@dbName@@@`;


DROP TABLE IF EXISTS `tb_abc`;

CREATE TABLE `tb_abc` (
  `id` varchar(36) NOT NULL,
  `days` int(11) DEFAULT NULL,
  `last_update_user` varchar(50) DEFAULT NULL,
  `last_update_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class MySqlSuperDao implements ISuperDao {
	/**
	 * 创建数据库(读SQL脚本)
	 * 
	 * @author lty
	 */
	@SuppressWarnings("finally")
	public boolean createMisDB(String name, String year) throws DbException,
			DaoException, SQLException {
		Connection conn = null;
		Statement stmt = null;
		boolean success = false;
		// 创建数据库名
		String dbName = name + "_" + year;
		try {
			List<String> sqlList = new ArrayList<String>();
			try {
				InputStream sqlFileIn = MySqlSuperDao.class
						.getResourceAsStream("/MySql/createDB.sql");
				// 将SQL脚本产生为list<String>

				StringBuffer sqlSb = new StringBuffer();
				byte[] buff = new byte[1024];
				int byteRead = 0;
				while ((byteRead = sqlFileIn.read(buff)) != -1) {
					sqlSb.append(new String(buff, 0, byteRead, "utf-8"));
				}

				String[] sqlArr = sqlSb.toString().split(
						"(;\\s*\\r\\n)|(;\\s*\\n)");

				// 替换数据库名
				int replace = 0;
				for (int i = 0; i < sqlArr.length; i++) {
					if (replace == 2) {
						break;
					}
					if (sqlArr[i].indexOf("@@@dbName@@@") > -1) {
						sqlArr[i] = sqlArr[i].replace("@@@dbName@@@", dbName);
						replace++;
					}
				}
				// 将数组转成LIST并且过滤LOCKTABLE 和注释
				for (int i = 0; i < sqlArr.length; i++) {
					String sql = sqlArr[i].replaceAll("--.*", "").trim();
					if (!sql.equals("") && sql.indexOf("LOCK TABLES") != 0
							&& sql.indexOf("UNLOCK TABLES") != 0
							&& sql.indexOf("/*") != 0) {
						sqlList.add(sql);
					}
				}
			} catch (Exception e) {
				System.out.println("error");
				return false;
			}
			// 创建数据库链接并执行SQL脚本
			conn = this.getConnection();
			stmt = null;
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			for (String sql : sqlList) {
				stmt.addBatch(sql);
			}
			stmt.executeBatch();
			success = true;
		} catch (Exception e) {
			// 如果报错,则删除D
			conn = null;
			conn = this.getConnection();
			stmt = null;
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			stmt.execute("drop database " + dbName);
			success = false;
		} finally {
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
			return success;
		}
	}

	/**
	 * 获取数据库链接
	 * 
	 * @author lty
	 * @time 2019-02-26 10:48:24
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private Connection getConnection() throws SQLException, IOException,
			ClassNotFoundException {
		Connection con = null;
		Class.forName("com.mysql.jdbc.Driver");

		Properties properties = new Properties();
		properties.load(MySqlSuperDao.class
				.getResourceAsStream("/MySql/DB.properties"));
		String url = properties.getProperty("url");
		String u = properties.getProperty("u");
		String p = properties.getProperty("p");
		con = DriverManager.getConnection("jdbc:mysql://" + url + "", u, p);
		return con;
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你可以使用Java的JDBC API来读取SQL脚本执行。以下是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class SqlScriptExecutor { public static void main(String[] args) throws Exception { // 读取SQL脚本文件 BufferedReader reader = new BufferedReader(new FileReader("script.sql")); String line = null; StringBuilder sql = new StringBuilder(); while ((line = reader.readLine()) != null) { sql.append(line); sql.append("\n"); } reader.close(); // 连接数据库执行SQL脚本 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); Statement stmt = conn.createStatement(); stmt.executeUpdate(sql.toString()); stmt.close(); conn.close(); } } ``` 在上面的代码中,我们首先使用`BufferedReader`类读取SQL脚本文件,并将其存储在一个`StringBuilder`对象中。然后,我们使用JDBC API连接到数据库,并使用`Statement`对象执行SQL脚本。最后,我们关闭`Statement`和`Connection`对象以释放资源。 ### 回答2: java读取sql脚本执行的代码可以使用JDBC(Java Database Connectivity)来实现。首先,我们需要创建一个JDBC连接,连接到数据库。然后,我们使用BufferedReader来读取sql脚本文件中的内容,并将其逐行存储在一个字符串中。接下来,我们可以使用JDBC的Statement或PreparedStatement对象来执行这些sql语句。 下面是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class SqlScriptRunner { public static void main(String[] args) { String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库连接URL String username = "username"; // 数据库用户名 String password = "password"; // 数据库密码 String scriptPath = "path/to/sql/script.sql"; // sql脚本文件路径 try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password); BufferedReader reader = new BufferedReader(new FileReader(scriptPath)); Statement statement = connection.createStatement()) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append(System.lineSeparator()); // 每行结束加入换行符 } String script = sb.toString(); statement.execute(script); System.out.println("Sql脚本执行成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们使用了try-with-resources语句来确保在使用后自动关闭数据库连接和文件读取器,并通过StringBuilder来构建sql脚本字符串。然后,我们使用Statement对象的execute方法来执行sql脚本。 请注意,这只是一个简单的示例,如果你的sql脚本包含有特殊的语句(如存储过程、触发器、函数等),则可能需要进行额外的处理。此外,为了安全起见,建议对从外部读取的sql脚本进行一定的验证和过滤,以防止SQL注入等安全问题的出现。 ### 回答3: 下面是一个用Java编写的读取SQL脚本执行的代码: ```java import java.io.*; import java.sql.*; public class SQLScriptExecutor { public static void main(String[] args) { try { // 创建数据库连接 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); // 读取SQL脚本文件 File sqlScriptFile = new File("script.sql"); BufferedReader reader = new BufferedReader(new FileReader(sqlScriptFile)); // 构建SQL语句 StringBuilder sqlScript = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sqlScript.append(line); sqlScript.append(" "); } // 执行SQL脚本 Statement statement = connection.createStatement(); statement.executeUpdate(sqlScript.toString()); // 关闭数据库连接 statement.close(); connection.close(); System.out.println("SQL脚本执行成功!"); } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 上述代码首先创建一个数据库连接,并使用`getConnection`方法根据数据库URL、用户名和密码获取连接。然后,打开并读取SQL脚本文件,逐行读取内容,并使用`StringBuilder`构建SQL语句。接下来,通过创建一个`Statement`对象,利用`executeUpdate`方法执行SQL脚本并更新数据库。最后,关闭数据库连接和文件读取器。 请注意,你需要将代码中的`"jdbc:mysql://localhost:3306/mydatabase"`替换为您的实际数据库URL,以及将`"username"`和`"password"`替换为您的数据库用户名和密码。另外,你需要将`"script.sql"`替换为实际的SQL脚本文件路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值