gpt4 book ai didi

java - 类.forName ("com.mysql.jdbc.Driver").newInstance()

转载 作者:行者123 更新时间:2023-11-29 01:07:19 25 4
gpt4 key购买 nike

我在 Netbeans 7.2 上遇到这个错误,它说 ClassNotFoundexception 和 InstantationException。我真的被困在这件事上了。请帮助我。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String driver = "com.mysql.jdbc.Driver";
con = null;
String username = "";
String password = "";

Class.forName("com.mysql.jdbc.Driver").newInstance();

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");
Statement st = con.createStatement();
ResultSet mar = st.executeQuery("SELECT * FROM table");


Gson gson = new GsonBuilder().create();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");

} catch (SQLException e) {
String message = e.getMessage();
}

最佳答案

这种简单的方法怎么样?!

java.sql.Driver d=new com.mysql.jdbc.Driver();

我也想知道你为什么要这样连接数据库?!最好让服务器管理它。

首先配置 context.xml (如果你使用的是 tomcat)像这样:

<context>
<Resource name="_ds" auth="Container" type="javax.sql.DataSource"
maxActive="128" maxIdle="32" username="_admin" password="qwerty" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/dbname"/>
</context>

然后,在 servlet/etc 中简单地从该资源获取连接,如下所示:

public void init() {
try {
_ds = (DataSource) InitialContext.lookup("java:/comp/env/_ds");
} catch (Exception ex) {
}
}

private javax.sql.DataSource _ds;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
/*String driver = "com.mysql.jdbc.Driver";
con = null;
String username = "";
String password = "";

Class.forName("com.mysql.jdbc.Driver").newInstance();

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");*/
Connection con=_ds.getConnection();
Statement st = con.createStatement();
ResultSet mar = st.executeQuery("SELECT * FROM table");


Gson gson = new GsonBuilder().create();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
con.close();
} catch (SQLException e) {
String message = e.getMessage();
}

顺便说一下,不要忘记在 <CATALINA_BASE>/lib 中编译 MySQL JDBC 驱动程序 jar 文件。文件夹。

关于java - 类.forName ("com.mysql.jdbc.Driver").newInstance(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19412135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com