英文:
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
- 创建连接对象
- 创建语句对象
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();
}
英文:
- Create Connection Object
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论