This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
ClassNotFoundException when using User Libraries in Eclipse build path
(2 answers)
How should I connect to JDBC database / datasource in a servlet based application?
(2 answers)
Closed 2 years ago.
i am creating simple crud using jsp servlet connect with mysql database. i ran into the problem with
ClassNotFoundException: com.mysql.jdbc.Driver i successfully added the mysql driver i attached with the screenshot image below.please have a look.
what i tried the code i attached below.
#WebServlet("/addServlet")
public class addServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PreparedStatement st1=null;
Connection con;
PrintWriter out = response.getWriter();
String sname =request.getParameter("sname");
String course =request.getParameter("course");
String addr =request.getParameter("address");
String mobile =request.getParameter("mno");
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/lblschool", "root","");
String query ="insert into student(sname,course,address,mno)values(?,?,?,?)";
st1= con.prepareStatement(query);
st1.setString(1, sname);
st1.setString(2, course);
st1.setString(3, addr);
st1.setString(4, mobile);
int k = st1.executeUpdate();
if(k ==1)
{
out.println("Thanks for registration ......");
String query2 = "select max(reg_id) from students";
Statement st1s = con.createStatement();
ResultSet rs1 = st1s.executeQuery( query2);
rs1.next( );
String reg_No = rs1.getString(1);
out.println("Your registration id is " + reg_No);
}
else
{
out.println("Cant' update");
}
}
catch(Exception ee)
{
System.out.println(ee.toString());
}
}
}
Try using this class:
com.mysql.cj.jdbc.Driver
Related
This question already has answers here:
How is driver class located in JDBC4
(3 answers)
Closed 4 years ago.
I am trying to understand JDBC internals, specifically, how is my JDBC driver being loaded if
1. I am not using Class.forName()
2. Checking for the jdbc.driver system property returns null.
I've tried checking my class path and printing the full list of system properties to the console for inspection as per https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html#registerDriver-java.sql.Driver- and https://db.apache.org/derby/docs/10.4/devguide/cdevdvlp40653.html
Below is the DBConnection constructor from DBConnection class
`public DBConnection() {
try {
this.conn = DriverManager.getConnection(JDBC_URL);
if (this.conn != null) {
System.out.println("Connection successful");
}
} catch(SQLException sqlex) {
System.out.println("Connection failed");
}
}`
Below is main()
public static void main(String[] args) {
DBConnection dbTest = new DBConnection();
String sysPropsString = System.getProperties().toString();
String[] propsArr = sysPropsString.split(",");
for(String property : propsArr) {
if (property.contains("class") && property.contains("path")
&& (property.contains("derby") || property.contains("drivers")))
System.out.println(property);
}
System.out.println("***********************************");
String sysDrivers = System.getProperty("jdbc.drivers");
System.out.println(sysDrivers);
}
I expected to have the derby jdbc driver printed to the console from the System.getProperty() call OR to find it somewhere on the classpath, but I see neither. How is the derby driver being loaded?
Below is the output:
Connection successful
java.class.path=/Users/aslotu/eclipse-workspace/Bullhorn/build/classes:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_cs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_de_DE.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_es.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_fr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_hu.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_it.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_ja_JP.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_ko_KR.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_pl.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_pt_BR.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_ru.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_zh_CN.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derbyLocale_zh_TW.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/db/lib/derby.jar
null
derby.jar contains file META-INF/services/java.sql.Driver which register org.apache.derby.jdbc.AutoloadedDriver.
This work because DriverManager use ServiceLoader.
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
I'm having issues connecting to an external IP address using JDBC. When I execute the following code, I get this error No suitable driver found for jdbc:mysql://52.206.157.109:3306/U054Jk
Code:
package util;
import java.sql.*;
public class db {
private static String server = "52.206.157.109";
private static String dbName = "U054Jk";
private static String userName = "secret";
private static String password = "secret";
private static Connection getCon() throws SQLException {
String host = "jdbc:mysql://" + server + ":3306/" + dbName;
Connection conn = DriverManager.getConnection(
host,
userName,
password
);
return conn;
}
public static ResultSet ExecQuery(String query) throws SQLException {
//Get the connection
Connection conn = getCon();
//Create the statement
Statement stmt = conn.createStatement();
//Execute the statement
ResultSet rs = stmt.executeQuery(query);
//Return ResultSet
return rs;
}
}
I can connect with my SQL client just fine using the credentials but can't quite figure out the JDBC string that I need for the URL. Thank you for your help.
Please add MySQL Connector in the classpath. Your project needs a JDBC driver implementing the interfaces of JDBC.
If you are using Apache Maven, add the following in the pom.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
Or else, download the jar from the link and add it to the classpath.
This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 7 years ago.
I'm trying to connect to a database in a Java Servlet, but I am unable to connect. I searched on google and each website is showing different way I don't know why.
Here is the code that I tried to connect, but nothing(data) is going to MySQL database rows.
public class DBConnection{
private static final long serialVersionUID = 1L;
private final Connection connection;
private final String dbURL = "jdbc:mysql://localhost:3306/Servlet";
private final String user = "root";
private final String pwd = "";
public DBConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(dbURL, user, pwd);
}
public Connection gC(){
return this.connection;
}
}
Here is I'm trying to insert data in database (but data is not adding to DB).
public class ReServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try{
String uName=req.getParameter("uName");
String uEmail=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
DBConnection conn=new DBConnection();
PreparedStatement ps;
ps = conn.gC().prepareStatement("insert into users(name,email,password) values (?,?,?)");
ps.setString(1, uName);
ps.setString(2, uEmail);
ps.setString(3, uPass);
ps.execute();
}catch(SQLException | ClassNotFoundException se){
se.printStackTrace();
}finally{
}
}
}
I also request to all, please give me simple and easy database connection example, about each website is showing with full registration or any other system. But I just want simple db connection example as I am trying in my code.
Edited
By replacing se.printStackTrace(); to this throw new RuntimeException(se); I'm getting this Exception java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
You nedd to register your driver with DriverManager like this:
Class c = Class.forName("com.mysql.jdbc.Driver");
DriverManager.registerDriver( c.newInstance() );
Please remember to close your connection in finally block.
previously i using this code to connect my database there is non error occur.
but comes to this DA files, its unable to connect to database.
i had go through most of the post but some of it i don't understand.[i'm just new to java]
i had try to use jdbc:derby://localhost:1527/societydb;create=true
but the same error occur again.
here's the code and <<< is the line the error point to.
private String host = "jdbc:derby://localhost:1527/societydb";
private String user = "nbuser";
private String password = "nbuser";
private String tableName = "MEMBER";
private void createConnection() {
try {
conn = DriverManager.getConnection(host, user, password);
System.out.println("*** Successfully established the connection to database. ***");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<Member> getMember() {
ArrayList<Member> memArray = new ArrayList<>();
try {
stmt = conn.prepareStatement("SELECT * FROM " + tableName);//<<< error pointing to here
ResultSet rs = stmt.executeQuery();
while (rs.next()){
Member m = new Member(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getInt(9), rs.getString(10), rs.getString(11));
memArray.add(m);}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE);
}
return memArray;
}
From Java documentation the drivers you need are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver.
Also it clearly states
Any JDBC 4.0 drivers that are found in your class path are automatically loaded.(However,
you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)
Note : JDBC 4.0 comes as a default package from Java 7 onwards.
As for your problem search for the classes mentioned above in your class path(Ctrl + N in Intellij Idea or Ctrl + R in Eclipse). If these classes are not present google them, download and add the jar files to your class path.
Just add these external jars:
derby.jar
derbyclient.jar
How to do it:
right click your project > Properties > Java Build Path > Libraries
click 'Add external jar'
go to C:\Program Files\Java\jdk1.8.0_65\db\lib
add the derby.jar and derbyclient.jar
I am having this error on Netbeans 7.2, it says that ClassNotFoundexception and InstantationException. I am really stuck on this matter. Kindly help me.
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();
}
What about this simple way?!
java.sql.Driver d=new com.mysql.jdbc.Driver();
I also wondered why do you connect to database with such this way?! It's better let server manage it.
First config the context.xml (if you are using tomcat) like this:
<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>
Then, simple get a connection from this resource in servlet/etc, like this:
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();
}
By the way, don't forget to compy the MySQL JDBC driver jar-file in <CATALINA_BASE>/lib folder.
All you need is Class.forName("com.mysql.jdbc.Driver")
This acts like class loader and load your driver class for you. For that you need to add the corresponding jar file(which has the driver implementation). So download and add mysql-connector.jar in your class path.
Note : If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver") statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
You might want to solve a bigger problem. You ought not enter configuration data such as database connection information directly in your servlet.
Are you using Tomcat? You can simply use JNDI. You will be able to change database details and drivers without having to recompile your servlet.
Here is the Tomcat 7.0 JNDI Datasource HOW-TO shows various ways in which you can get a Connection to your database.
On that page, you have a code example of how to get a Connection (Oracle 8i, 9i & 10g -> Part 3), and how to write a MySQL specific configuration.
Make sure to download a correct MySQL jar and place it in your Tomcat's lib/ directory (or alternatively your WAR's WEB-INF/lib).
You need to add mysqlconnector.jar file found here: ( http://dev.mysql.com/downloads/connector/j/ ) into your lib folder of your project. Include it with your project and then you can access your connection with database.
Add that jar into the buildpath.