简体   繁体   中英

connecting to mysql in java

I am very beginner in java programming. I use eclipse IDE to write my code.I create a project and want to connect to mysql. At first,i install apache 9 and then open eclipse and create my project and then install mysql 8. When I run my code,"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver" is shown. I have taken image from my project.

https://www.imgurl.ir/uploads/r22886_.jpg

Please help me. Thank you.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" buffer="none"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"  %>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<html>
<head>
<title>First java web</title>
</head>
<body>

<%
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ex)
{
    out.print(ex.toString());
}
catch(Exception e)
{
    out.print(e.toString());
}
%>

</body>
</html>

Please put your jdbc connection in Servlet or better yet create a database layer in your code that handles db connection and data manipulations after you get your data. Now to answer your question

import java.sql.*;  

class MysqlCon{  

public static void main(String args[]){  
  try{  
      Class.forName("com.mysql.jdbc.Driver");  
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");  

     //here mydb is database name, root is username and password  
     Statement stmt=con.createStatement();  
     ResultSet rs=stmt.executeQuery("select * from emp");  

     while(rs.next())  
         System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
         con.close();  
     } catch(Exception e) { 
      System.out.println(e);
    }  
  }  
}  

It looks like you are not familiar with Servlets and Patterns like MVC. I recommend you to have a look at some tutorials because extensibility is a very important point in software development. The way you are starting in your example will result in spagehetti code it won't be fun to continue developing. As a Tip: If you want to develop in java you can also have a look at the Spring tool suite (Sts) Framework. I makes java development very easy and you got some great tutorial to have a quick start. Python with Flask is also a good way to start with web development.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM