我是一个java初学者,试图在数据库中插入一行。这是我第一次在java中执行插入操作。在大约 2 小时的时间里,我在谷歌上搜索并感到沮丧,但无法解决我的错误。我调用我的 friend ,他在团队查看器中为我提供了实时支持,并且只在我的程序中添加了一行代码。
Class.forName("com.mysql.jdbc.Driver")
任何人都可以解释一下为什么我们需要在连接字符串之前将其包含在我的代码中。是否有必要每次都将我的代码放在那里。请详细解释一下。
最佳答案
这里有一些非常简化的代码,说明了驱动程序初始化的工作原理。有 3 个类,请将每个类放入一个适当命名的文件中。
import java.util.HashMap;
import java.util.Map;
public class DriverMgr {
private static final Map<String, Class<?>> DRIVER_MAP = new HashMap<String, Class<?>>();
public static void registerDriver(final String name, final Class<?> cls) {
DRIVER_MAP.put(name, cls);
}
public static Object getDriver(final String name) {
final Class<?> cls = DRIVER_MAP.get(name);
if (cls == null) {
throw new RuntimeException("Driver for " + name + " not found");
}
try {
return cls.newInstance();
} catch (Exception e) {
throw new RuntimeException("Driver instantiation failed", e);
}
}
}
public class MysqlDriver {
static {
// hello, I am a static initializer
DriverMgr.registerDriver("mysql", MysqlDriver.class);
}
@Override
public String toString() {
return "I am the mysql driver";
}
}
public class TestProg {
public static void main(final String... args) {
try {
Class.forName("MysqlDriver"); // try with or without this
} catch (Exception e) {
throw new RuntimeException("Oops, failed to initialize the driver");
}
System.out.println(DriverMgr.getDriver("mysql"));
}
}
当您调用 Class.forName 时,将加载驱动程序类并执行静态初始化程序。这反过来又向驱动程序管理器注册驱动程序类,以便管理器现在知道它。显然,这只需要完成一次。
关于java - 找不到适用于 jdbc :mysql://localhost/db 的合适驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031115/