Java USES JDBC to connect to a database

  • 2020-04-01 03:29:07
  • OfStack

This article illustrates how Java USES JDBC to connect to a database, which is a very useful and important technique in Java database programming. Share with you for your reference. The details are as follows:

JDBC(Java Data Base Connectivity) is a database connection that is typically used when writing web applications or Java applications to connect to a database. The general steps to connect to a database using JDBC are:

1. Load the driver


Class.forName(driver);

2. Create a connection object


Connection con = DriverManager.getConnection(url,username,password);

3, create SQL statement execution object
Execute the SQL statement
5. Process the execution results
6. Close related connection objects (in the reverse order declared)

The following is an example of establishing a connection to a MySQL database. The process for other databases is similar:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection
{
public static void main(String[] args)
{
String driver = "com.mysql.jdbc.Driver";
//Localhost refers to the native, or can be replaced by the local IP address, 3306 is the default port number of the MySQL database, and "user" is the name of the database to connect to
String url = "jdbc:mysql://localhost:3306/user";
//Enter the username and password for the database
String username = "test";
String password = "test";
String sql = "select * from user";//Write the SQL statement to execute, where all users are queried for information from the user table
try
{
Class.forName(driver);//Load the driver, using the method of implicitly registering the driver
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
Connection con = DriverManager.getConnection(url,username,password);//Create a connection object
Statement st = con.createStatement();//Create the SQL execution object
ResultSet rs = st.executeQuery(sql);//Execute the SQL statement and return the result set
while(rs.next())//Iterate over the output of the result set
{
System.out.println("username: "+rs.getString(1));//The data is obtained by the number of the column
System.out.println("useradd: "+rs.getString("useradd"));//Get data by column name
System.out.println("userage: "+rs.getInt("userage"));
}
//Close the relevant object
if(rs != null)
{
try
{
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
if(st != null)
{
try
{
st.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
if(con !=null)
{
try
{
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

I believe that this article has a certain reference value for everyone's Java database programming.


Related articles: