JAVA案例:
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author lmz
* context:
* @projectName BladeX-Boot-kk
* @data 2023/5/10 9:27
*/
public class InnoDBExample {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test";
private static final String JDBC_USERNAME = "root";
private static final String JDBC_PASSWORD = "root";
public static void main(String[] args) throws SQLException {
// 连接数据库
Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
// 开启事务
connection.setAutoCommit(false);
try {
Map<String, Map<String, Object>> a = new HashMap<>();
// 创建表
Statement createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `user` (`id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// 插入数据
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO `user` (`name`) VALUES (?)");
preparedStatement.setString(1, "Alice");
preparedStatement.executeUpdate();
// 提交事务
connection.commit();
} catch (Exception e) {
// 发生异常回滚事务
connection.rollback();
e.printStackTrace();
} finally {
// 关闭连接
connection.close();
}
}
}