Method of JSP Connecting MYSQL Database with JDBC

  • 2021-10-15 11:10:38
  • OfStack

This article illustrates how JSP uses JDBC to connect MYSQL database. Share it for your reference, as follows:

1. The MySQL JDBC driver mysql-connector-java-*. jar can be downloaded at http://www.mysql.com/products/connector-j/index.html, if I downloaded mysql-connector-java-5. 1.18-bin.jar and added under ClassPath, or added to the project.

2. Register the JDBC driver


try { 
   Class.forName("com.mysql.jdbc.Driver"); 
} 
catch(ClassNotFoundException e) { 
   System.out.println(" Driver not found "); 
}

3. Provide JDBC URL

jdbc: mysql://Hostname: Port number/database name? user=*** & password=*** & useUnicode=true & characterEncoding=UTF8

Port number: The default value of MySQL is 3306

useUnicode, characterEncoding: If you want to access Chinese, you must use it, indicating whether Unicode is used and specifying the encoding method.

4. Get Connection from DriverManager

You can pass JDBC URL directly into DriverManager. getConnection () to get an Connection object, such as:


try { 
   String url = "jdbc:mysql://localhost:3306/GUESTBOOK?user=root&password=123456"; 
   Connection conn = DriverManager.getConnection(url); 
   if(!conn.isClosed()) 
   System.out.println(" Database connection succeeded !");
   conn.close(); 
} 
catch(SQLException e) { 
   .... 
}

You can also pass userName and password into DriverManager. getConnection () to get an Connection object, such as:


String url = "jdbc:mysql://localhost:3306/AddressBook"; 
String user = "ZhuJun"; 
String password = "123456"; 
Connection conn = DriverManager.getConnection(url, user, password);

1 complete example:


import java.sql.*;
public class TestJDBC {
 public static void main(String[] args) throws Exception {
   Class.forName("com.mysql.jdbc.Driver");
   String url = "jdbc:mysql://localhost:3306/2";
   String user = "root";
   String password = "19870714";
   Connection conn = DriverManager.getConnection(url, user, password);
   if(!conn.isClosed())
   {
   System.out.println("success");
   }
   conn.close();
 }
}

I hope this article is helpful to everyone's JSP programming.


Related articles: