简体   繁体   中英

How to create a database if it does not exist with springboot/JPA and SQL Server?

I am surprised I haven't found an SO question that answers this. I am trying to connect a springboot/JPA application to an SQL Server on my local machine. I have the application setup so that it can connect to a database if it it exists, but if I change the JDBC URL to create the database if it doesn't exist then it fails. Here is what the properties look like when it fails.

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=testing;createDatabaseIfNotExist=true;
spring.datasource.username=hello
spring.datasource.password=Hello1234
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2008Dialect
spring.jpa.show-sql=true

Here is a snippet of the error I receive when starting the app:

com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'hello'. ClientConnectionId:971a3369-258b-4713-bddc-cda559b9fe94 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262) ~[mssql-jdbc-8.4.0.jre11.jar:na] at com.microsoft.sqlserver.jdbc.TDSTokenHandle

If anybody has any thoughts as to how I can change this so the database is created if it does not exist I would be very thankful. Thanks in advnace.

In practice your application should never create your database so its not really a problem most of the time(Outside small databases like sqlite3). Different databases would handle this situation differently as well.

In your case I do not see this as a valid jdbc parameter in the documentation . I would recommend creating the database in advance with a privileged user separate from your application user.

I don't think a database can be created using JPA. It has to be created manually or in some other ways, but JPA won't do that for you.

And it would be a bad practice as well to create the database using the application itself, and the use of same credentials.

Yes, definitely you can auto-create a database with JPA for that

spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=testing;
createDatabaseIfNotExist=true;

line should be changed to:

spring.datasource.url=jdbc:sqlserver://localhost:1433
/testing?createDatabaseIfNotExist=true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM