使用Hibernate在PostgreSQL中创建数据库。

huangapple go评论68阅读模式
英文:

Creating database using hibernate in postgres

问题

我正在尝试使用本地查询创建数据库。

我的代码:

@Service
public class DatabaseService {

    @PersistenceContext
    private EntityManager em;

    public void create() {
        String sql = "CREATE DATABASE MYDATABASE TEMPLATE PATTERN";
        Query q = em.createNativeQuery(sql);

        q.executeUpdate();
    }
}

当我运行这个代码时,我收到错误消息:"应在事务中运行插入/更新操作"。

当我添加 @Transactional 注解时,我收到错误消息:"无法在事务中创建数据库"。

我应该怎么办?

英文:

I am trying to create database using native query.

My code:

@Service
public class DatabaseService {

    @PersistenceContext
    private EntityManager em;

    public void create() {
        String sql = "CREATE DATABASE MYDATABASE TEMPLATE PATTERN";
        Query q= em.createNativeQuery(sql);

        q.executeUpdate();
    }
}

When I run this I get error "insert/update should be run in transaction"

when i add @transacional i get "database cannot be created in transaction"

What should i do?

答案1

得分: 1

  1. 创建连接对象
  2. 创建语句对象
Connection Conn = DriverManager.getConnection("jdbc:mysql://localhost:3306");
try {
   Statement Stmt = Conn.createStatement();
   Stmt.execute("CREATE DATABASE db_name");
   Stmt.execute("CREATE TABLE db_name (message char(31))");
   Stmt.executeUpdate("INSERT INTO db_name VALUES ('Hello World')");
   Conn.commit();
} catch (SQLException exception) {
   Stmt.execute("OPEN DATABASE db_name");
} finally {
   Conn.close();
}
英文:
  1. Create Connection Object
  2. Creating your Statement Object
Connection Conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306”);
try {
   Statement Stmt = Conn.createStatement();
   Stmt.execute(“CREATE DATABASE db_name”);
   Stmt.execute(“CREATE TABLE db_name (message char(31))”);
   Stmt.executeUpdate (“INSERT INTO db_name VALUES (”Hello World”)”);
   Conn.commit();
} catch (SQLException exception) {
   Stmt.execute(“OPEN DATABASE db_name”);
} finally {
   Conn.close();
}

答案2

得分: 0

修改您的查询为:

String sql = "CREATE DATABASE MYDATABASE;";

因为您正在创建数据库。

英文:

modify your query to

String sql = "CREATE DATABASE MYDATABASE ";

as u r creating database.

huangapple
  • 本文由 发表于 2020年9月21日 17:30:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63989573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定