K S*_*ggs 7 java mysql database jdbc
你能帮忙解决这个问题吗?
我正在尝试创建然后使用名为TIGER的数据库.
如果我在MySQL中创建数据库并且运行完美,我没有问题.
我想做的是从Java创建它.因此,当代码第一次运行时,它会在初始启动时创建数据库.如果可能的话,我想用一个干净的方法把它装箱.
有人可以告诉我你实际定位代码的位置
这是代码
private String jdbcDriver = "com.mysql.jdbc.Driver";
private String dbAddress = "jdbc:mysql://localhost:3306/";
private String dbName = "TIGER";
private String userName = "root";
private String password = "";
private PreparedStatement statement;
private ResultSet result;
private Connection con;
public DbStuff() {
try {
Class.forName(jdbcDriver);
con = DriverManager.getConnection(dbAddress + dbName, userName, password);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
这是创建数据库的代码
con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
statement = Conn.createStatement();
int myResult = statement.executeUpdate("CREATE DATABASE TIGER");
Run Code Online (Sandbox Code Playgroud)
在此先感谢,任何和所有的帮助表示赞赏
对于这些错误感到抱歉,因为我是一位长期读者,但却是一位新作家.
当我尝试运行代码的主要部分时,它会生成一个SQLException,因为数据库不存在.此时我想捕获异常并在那时创建数据库.但是,当我尝试这个时,它不会创建数据库.
小智 13
你总是可以跑
int myResult = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS TIGER;")
Run Code Online (Sandbox Code Playgroud)
如果在项目启动时运行它,它将只检查数据库是否存在,如果不存在,它将创建新数据库.
供参考:http://dev.mysql.com/doc/refman/5.0/en/create-database.html
小智 8
我建议使用此代码段
private String jdbcDriver = "com.mysql.jdbc.Driver";
private String dbAddress = "jdbc:mysql://localhost:3306/TIGER?createDatabaseIfNotExist=true";
private String userName = "root";
private String password = "";
private PreparedStatement statement;
private ResultSet result;
private Connection con;
public DbStuff() {
try {
Class.forName(jdbcDriver);
con = DriverManager.getConnection(dbAddress, userName, password);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用此代码。
public class DbStuff {
private static String jdbcDriver = "com.mysql.jdbc.Driver";
private static String dbName = "TIGER";
public static void main(String[] args) throws Exception {
Class.forName(jdbcDriver);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=");
Statement s = conn.createStatement();
int Result = s.executeUpdate("CREATE DATABASE "+dbName);
}
}
Run Code Online (Sandbox Code Playgroud)