上述链接问题不重复,因为链接的答案会完成我在此问题中所做的一切。我的解决方案涉及一些外部代码更改,但没有回答详细阐述。
我在StackOverflow上阅读了许多其他帖子,以及关于如何使用Java创建本地数据库的Web上的教程。据我所知,我正确地做到了这一点:
private static final String USER = "root";
private static final String PASS = "password";
private static final String DB_URL = "jdbc:mysql://localhost/?user=" + USER + "&password=" + PASS;
private final String DB_NAME;
public MyDBClass(String subName) {
DB_NAME = "`SOOT " + subName + "`";
Connection conn;
Statement stmt;
try {
Class.forName(java.sql.Driver.class.getName()); // Line 38
Logger.getGlobal().finer("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS); // Line 41
Logger.getGlobal().finer("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE IF NOT EXISTS " + DB_NAME
+ " DEFAULT CHARACTER SET utf8"
+ " DEFAULT COLLATE utf8_unicode_ci";
stmt.executeUpdate(sql);
} catch (Exception ex) {
Logger.getGlobal().log(Level.SEVERE, "Could not create database.", ex);
}
}
但是当我运行它时,我得到了:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/?user=root&password=password
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at my.app.MyDBClass.<init>(MyDBClass.java:41)
at my.app.Main.main(Main.java:34)
我尝试在第38行使用Class.forName("com.mysql.jdbc.Driver");
代替Class.forName(java.sql.Driver.class.getName());
,但我得到了:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at my.app.MyDBClass.<init>(Language.java:38)
at my.app.Main.main(Main.java:34)