Reputation: 944
I tried to connect to database using jdbc, but I have still error next to import java.sql.Connection;
The import java sql connection conflicts with a type defined in the same file
I have mysql-connector-java-5.1.40-bin.jar
kept in Apache Tomcat Library.
Here is my code:
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
}
}
Upvotes: 2
Views: 4325
Reputation: 9658
This is because your class is also named as Connection
and hence is creating the conflict while creating the object.
The line which must be creating the conflict is as follows:
Connection conn = null;
You can modify this as follows:
java.sql.Connection conn = null;
Or alternatively, rename your class to DBConnection
or something else.
Upvotes: 1