gpt4 book ai didi

java - 连接到 DB java - 导入 java sql 连接与同一文件中定义的类型冲突

转载 作者:行者123 更新时间:2023-11-28 23:21:21 24 4
gpt4 key购买 nike

我尝试使用 jdbc 连接到数据库,但是 import java.sql.Connection;

旁边仍然有错误

The import java sql connection conflicts with a type defined in the same file

我将 mysql-connector-java-5.1.40-bin.jar 保存在 Apache Tomcat 库中。

这是我的代码:

package demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class Connect
*/
@WebServlet("/Connect")
public class Connection extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Connection() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
out.println("Can't load database driver");
//e.printStackTrace();
String strClassPath = System.getProperty("java.class.path");

System.out.println("Classpath is " + strClassPath);
return;
}

Connection conn = null;

try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/webshop", "root", "root");
} catch (SQLException e) {
out.println("Can't connect to database.");
return;
}

out.println("Connected to database.");

try {
conn.close();
} catch (SQLException e) {

}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

最佳答案

这是因为您的类也被命名为 Connection,因此在创建对象时产生了冲突。

产生冲突的行如下:

Connection conn = null; 

您可以按如下方式修改:

java.sql.Connection conn = null;

或者,将您的类重命名为 DBConnection 或其他名称。

关于java - 连接到 DB java - 导入 java sql 连接与同一文件中定义的类型冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41469831/

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