How to connect MySQL database with java

Several methods of Java connecting database

* description

1. Take MySQL database as an example

2. There are four steps:

Establish database connection,

Submit sql to database

Processing the results returned by the database

Close database connection



1. Establish database connection

Just two steps, register the driver for the database, and then create a database connection

Example code:

  String url="jdbc:mysql://localhost:3306/test";

                   String Driver="com.mysql.jdbc.Driver";

                   String username="root";

                   String password="123456";



                   Connection conn=DriverManager.getConnection(url,username,password);
Method 1



 String url="jdbc:mysql://localhost:3306/test";

                   String username="root";

                   String password="123456";


                   new com.mysql.jdbc.Driver();

                   Connection conn=DriverManager.getConnection(url,username,password);
Method two



First, the class of MySQL driver is dynamically loaded through the forName() static method of java.lang.Class class. This class will be automatically registered in DriverManager, and then the Connection type object is obtained through DriverManager

2. High efficiency through database connection pool

The principle is to modify the context.xml file under the conf directory of Tomcat server to configure

Configured Code:

 <Context reloadable="true">


    <!-- Default set of monitored resources -->



    <Resource name="jdbc/mysql" auto="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="123456" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"/>


    <!-- Uncomment this to disable session persistence across Tomcat restarts -->


    <Manager pathname="" />



    <!-- Uncomment this to enable Comet connection tacking (provides events

         on session expiration as well as webapp lifecycle) -->


    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />






Get the database connection object in the connection pool through the data source object

Context context=new InitialContext();

DataSource ds=(DataSource) context.lookup("java:/comp/env/jdbc/mysql");

Connection conn=ds.getConnection();


3. Other steps will be described later

2, To be added later

Tags: Java Database MySQL JDBC

Posted on Fri, 03 Apr 2020 16:30:50 -0700 by adamata