San*_*Ryu 0 java database exists database-engine
我有一个大问题......我有一个数据库java程序创建。
我想知道数据库是否存在,如果存在只是连接,如果不创建它。
我试过这个:
if (dbName.exists() == false) {}
Run Code Online (Sandbox Code Playgroud)
这就是全部代码...
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");
Run Code Online (Sandbox Code Playgroud)
这是它的备份代码,只是为了现在工作......部分代码有效!
conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);
System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);
Run Code Online (Sandbox Code Playgroud)
但我想要这样的东西:
FILE dbName = new FILE (url);
Statement stmt = new Statement;
if (dbName.exists() == true)
System.out.println("Database exists ! Connecting ... ");
else {
String sql = "CREATE DATABASE "+url;
stmt.executeUpdate (sql);
}
Run Code Online (Sandbox Code Playgroud)
我不想将带有密码和用户名的 url 放在同一个地方......因为它们是从外部提供的,但这已经实现并有效。
所以我想在 2 和平,1 Connect "jdbc:mysql://localhost:3306/"; 没有 URL 是数据库名称......然后如果一个数据库不存在,那么就创建那个名称。
它不起作用......没有进入else更多,并说Exeption Database已经存在。
非常感谢你。
如果是 MySQL 数据库,下面的代码应该可以工作。其他数据库可能会给出不同的错误代码,但大致的方式应该是清楚的。重要的是您最初连接到实例,而不是特定的数据库。要创建表,您需要连接到新创建的数据库。您不能使用我在示例中使用的实例连接来创建表:
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/",
"root", "admin");
statement = connection.createStatement();
String sql = "CREATE DATABASE DBNAME";
//To delete database: sql = "DROP DATABASE DBNAME";
statement.executeUpdate(sql);
System.out.println("Database created!");
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
} catch (ClassNotFoundException e) {
// No driver class found!
}
// close statement & connection
Run Code Online (Sandbox Code Playgroud)