search
HomeJavajavaTutorialDetailed explanation of how to use Java to query, modify and connect MySQL

This article mainly introduces how to connect, query and modify the MySQL database in Java. Friends in need can refer to

0. General process:

 (1) Call the Class.forName() method to load the driver.

 (2) Call the getConnection() method of the DriverManager object to obtain a Connection object.

 (3) Create a Statement object and prepare a SQL statement. This SQL statement can be a Statement object (a statement to be executed immediately), a PreparedStatement statement (a precompiled statement) or a CallableStatement object (a stored procedure call). statement).

 (4) Call methods such as excuteQuery() to execute SQL statements and save the results in the ResultSet object; or call methods such as executeUpdate() to execute SQL statements without returning the results of the ResultSet object.

 (5) Perform display and other equivalent processing on the returned ResultSet object.

 (6) Release resources.

1. Connect to the database

 (1) Download the Mysql connection driver

After downloading, place it in F:\Doctoral Research Unzip it in Information\Database Learning\mysql related program files.

 (2) Load the JDBC driver

Operation method: In Eclipse, select the corresponding project, click Java Build Path in Project-Properties, and add mysql-connector-java- in Libraries 5.1.21-bin.jar, click OK.

 (3) Build a simple database as follows:


import java.sql.*;
public class GetConnection {
  public static void main(String[] args){
    try{
      //调用Class.forName()方法加载驱动程序
      Class.forName("com.mysql.jdbc.Driver");
      System.out.println("成功加载MySQL驱动!");
    }catch(ClassNotFoundException e1){
      System.out.println("找不到MySQL驱动!");
      e1.printStackTrace();
    }
    String url="jdbc:mysql://localhost:3306/mysql";  //JDBC的URL  
    //调用DriverManager对象的getConnection()方法,获得一个Connection对象
    Connection conn;
    try {
      conn = DriverManager.getConnection(url,  "root","");
      //创建一个Statement对象
      Statement stmt = conn.createStatement(); //创建Statement对象
      System.out.print("成功连接到数据库!");
      stmt.close();
      conn.close();
    } catch (SQLException e){
      e.printStackTrace();
    }
  }
}

2. Query the data table

When querying a data table, you need to use the ResultSet interface, which is similar to a data table. Through the instance of this interface, you can obtain the retrieval result set and the interface information of the corresponding data table.


import java.sql.*;
public class SelectTable {
  public static void main(String[] args){
    try{
      //调用Class.forName()方法加载驱动程序
      Class.forName("com.mysql.jdbc.Driver");
      System.out.println("成功加载MySQL驱动!");
      String url="jdbc:mysql://localhost:3306/aniu";  //JDBC的URL  
      Connection conn;
      conn = DriverManager.getConnection(url,  "root","");
      Statement stmt = conn.createStatement(); //创建Statement对象
      System.out.println("成功连接到数据库!");
      String sql = "select * from stu";  //要执行的SQL
      ResultSet rs = stmt.executeQuery(sql);//创建数据对象
        System.out.println("编号"+"\t"+"姓名"+"\t"+"年龄");
        while (rs.next()){
          System.out.print(rs.getInt(1) + "\t");
          System.out.print(rs.getString(2) + "\t");
          System.out.print(rs.getInt(3) + "\t");
          System.out.println();
        }
        rs.close();
        stmt.close();
        conn.close();
      }catch(Exception e)
      {
        e.printStackTrace();
      }
  }
}

3. Modify and delete the database


//修改删除数据
import java.sql.*;
public class UpdateDeleteDemo {
  public static void main(String[] args)throws Exception{
    try{
      //调用Class.forName()方法加载驱动程序
      Class.forName("com.mysql.jdbc.Driver");
      System.out.println("成功加载MySQL驱动!");
      String url="jdbc:mysql://localhost:3306/aniu";  //JDBC的URL  
      Connection conn;
      conn = DriverManager.getConnection(url,  "root","");
      Statement stmt = conn.createStatement(); //创建Statement对象
      System.out.println("成功连接到数据库!");
      //查询数据的代码
      String sql = "select * from stu";  //要执行的SQL
      ResultSet rs = stmt.executeQuery(sql);//创建数据对象
        System.out.println("编号"+"\t"+"姓名"+"\t"+"年龄");
        while (rs.next()){
          System.out.print(rs.getInt(1) + "\t");
          System.out.print(rs.getString(2) + "\t");
          System.out.print(rs.getInt(3) + "\t");
          System.out.println();
        }
      //修改数据的代码
      String sql2 = "update stu set name=? where number=?";
      PreparedStatement pst = conn.prepareStatement(sql2);
      pst.setString(1,"8888");
      pst.setInt(2,198);
      pst.executeUpdate();
      //删除数据的代码
      String sql3 = "delete from stu where number=?";
      pst = conn.prepareStatement(sql3);
      pst.setInt(1,701);
      pst.executeUpdate();
      ResultSet rs2 = stmt.executeQuery(sql);//创建数据对象
      System.out.println("编号"+"\t"+"姓名"+"\t"+"年龄");
      while (rs.next()){
        System.out.print(rs2.getInt(1) + "\t");
        System.out.print(rs2.getString(2) + "\t");
        System.out.print(rs2.getInt(3) + "\t");
        System.out.println();
      }
      rs.close();
      stmt.close();
      conn.close();
      }catch(Exception e)
      {
        e.printStackTrace();
      }
  }
}

The above is the detailed content of Detailed explanation of how to use Java to query, modify and connect MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment