Home Java javaTutorial Detailed explanation of how to use Java to query, modify and connect MySQL

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

Jul 18, 2017 am 09:32 AM
java mysql conduct

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();
    }
  }
}
Copy after login

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();
      }
  }
}
Copy after login

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();
      }
  }
}
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
What are the advantages of using Java for web applications that need to run on different servers? What are the advantages of using Java for web applications that need to run on different servers? May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

MySQL vs. Oracle: Understanding Licensing and Cost MySQL vs. Oracle: Understanding Licensing and Cost May 03, 2025 am 12:19 AM

MySQL uses GPL and commercial licenses for small and open source projects; Oracle uses commercial licenses for enterprises that require high performance. MySQL's GPL license is free, and commercial licenses require payment; Oracle license fees are calculated based on processors or users, and the cost is relatively high.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence? What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence? May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

How does platform independence simplify deployment of Java applications? How does platform independence simplify deployment of Java applications? May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

MySQL vs. phpMyAdmin: Understanding the Key Differences MySQL vs. phpMyAdmin: Understanding the Key Differences May 06, 2025 am 12:17 AM

MySQL is a database management system, and phpMyAdmin is a web tool for managing MySQL. 1.MySQL is used to store and manage data and supports SQL operations. 2.phpMyAdmin provides a graphical interface to simplify database management.

Navicat and MySQL: A Perfect Partnership Navicat and MySQL: A Perfect Partnership May 05, 2025 am 12:09 AM

Navicat and MySQL are perfect matches because they can improve database management and development efficiency. 1.Navicat simplifies MySQL operations and improves work efficiency through graphical interfaces and automatic generation of SQL statements. 2.Navicat supports multiple connection methods, which facilitates local and remote management. 3. It provides powerful data migration and synchronization capabilities, suitable for advanced usage. 4.Navicat helps with performance optimization and best practices such as regular backup and query optimization.

MySQL: A Practical Application of SQL MySQL: A Practical Application of SQL May 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

10 latest tools for web developers 10 latest tools for web developers May 07, 2025 pm 04:48 PM

Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.

See all articles