0

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?

2 Answers 2

1
  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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

modify your query to

String sql = "CREATE DATABASE MYDATABASE ";

as u r creating database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.