Home Java javaTutorial Detailed explanation of how java implements basic operations on mysql

Detailed explanation of how java implements basic operations on mysql

May 11, 2017 am 09:38 AM
java mysql Add, delete, modify and check

This article mainly introduces the method of using java to operate mysql to add, delete, modify and check, and analyzes the specific implementation techniques and related precautions for java to operate mysql database to add, delete, modify and check in the form of examples. Friends in need can refer to the following

The example of this article describes the method of using java to operate mysql to implement addition, deletion, modification and query. Share it with everyone for your reference, the details are as follows:

First, you need to import the jar package that connects MySQL and Java (mysql-connector-java-5.1.6-bin.jar) into the project .

package com.cn.edu;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class helloworld {
  private Connection conn = null;
  PreparedStatement statement = null;
  // connect to MySQL
  void connSQL() {
    String url = "jdbc:mysql://localhost:3306/hello?characterEncoding=UTF-8";
    String username = "root";
    String password = "root"; // 加载驱动程序以连接数据库
    try {
      Class.forName("com.mysql.jdbc.Driver" );
      conn = DriverManager.getConnection( url,username, password );
      }
    //捕获加载驱动程序异常
     catch ( ClassNotFoundException cnfex ) {
       System.err.println(
       "装载 JDBC/ODBC 驱动程序失败。" );
       cnfex.printStackTrace();
     }
     //捕获连接数据库异常
     catch ( SQLException sqlex ) {
       System.err.println( "无法连接数据库" );
       sqlex.printStackTrace();
     }
  }
  // disconnect to MySQL
  void deconnSQL() {
    try {
      if (conn != null)
        conn.close();
    } catch (Exception e) {
      System.out.println("关闭数据库问题 :");
      e.printStackTrace();
    }
  }
  // execute selection language
  ResultSet selectSQL(String sql) {
    ResultSet rs = null;
    try {
      statement = conn.prepareStatement(sql);
      rs = statement.executeQuery(sql);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return rs;
  }
  // execute insertion language
  boolean insertSQL(String sql) {
    try {
      statement = conn.prepareStatement(sql);
      statement.executeUpdate();
      return true;
    } catch (SQLException e) {
      System.out.println("插入数据库时出错:");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("插入时出错:");
      e.printStackTrace();
    }
    return false;
  }
  //execute delete language
  boolean deleteSQL(String sql) {
    try {
      statement = conn.prepareStatement(sql);
      statement.executeUpdate();
      return true;
    } catch (SQLException e) {
      System.out.println("插入数据库时出错:");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("插入时出错:");
      e.printStackTrace();
    }
    return false;
  }
  //execute update language
  boolean updateSQL(String sql) {
    try {
      statement = conn.prepareStatement(sql);
      statement.executeUpdate();
      return true;
    } catch (SQLException e) {
      System.out.println("插入数据库时出错:");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("插入时出错:");
      e.printStackTrace();
    }
    return false;
  }
  // show data in ju_users
  void layoutStyle2(ResultSet rs) {
    System.out.println("-----------------");
    System.out.println("执行结果如下所示:");
    System.out.println("-----------------");
    System.out.println(" 用户ID" + "/t/t" + "淘宝ID" + "/t/t" + "用户名"+ "/t/t" + "密码");
    System.out.println("-----------------");
    try {
      while (rs.next()) {
        System.out.println(rs.getInt("ju_userID") + "/t/t"
            + rs.getString("taobaoID") + "/t/t"
            + rs.getString("ju_userName")
             + "/t/t"+ rs.getString("ju_userPWD"));
      }
    } catch (SQLException e) {
      System.out.println("显示时数据库出错。");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("显示出错。");
      e.printStackTrace();
    }
  }
  public static void main(String args[]) {
    helloworld h = new helloworld();
    h.connSQL();
    String s = "select * from ju_users";
    String insert = "insert into ju_users(ju_userID,TaobaoID,ju_userName,ju_userPWD) values("+8329+","+34243+",'mm','789')";
    String update = "update ju_users set ju_userPWD =123 where ju_userName= 'mm'";
    String delete = "delete from ju_users where ju_userName= 'mm'";
    if (h.insertSQL(insert) == true) {
      System.out.println("insert successfully");
      ResultSet resultSet = h.selectSQL(s);
      h.layoutStyle2(resultSet);
    }
    if (h.updateSQL(update) == true) {
      System.out.println("update successfully");
      ResultSet resultSet = h.selectSQL(s);
      h.layoutStyle2(resultSet);
    }
    if (h.insertSQL(delete) == true) {
      System.out.println("delete successfully");
      ResultSet resultSet = h.selectSQL(s);
      h.layoutStyle2(resultSet);
    }
    h.deconnSQL();
  }
}
Copy after login

notice:

1. The commonly used driver now is com.mysql.jdbc.Driver, Although the previous org driver encapsulated com.mysql.jdbc.Driver, it was not easy to use and was outdated.

2. prepareStatement(sql) is a subclass of statement, which is easier to use than statement.

3. If the int value is defined in the database, then the int must be mentioned separately in the sql statement. Such as "....values("+8329+","+34243+",'mm','789')"

【Related recommendations】

1. JavaFree Video Tutorial

2. Comprehensive analysis of Java annotations

3. JAVA Tutorial Manual

The above is the detailed content of Detailed explanation of how java implements basic operations on 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 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
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

What do laravel read? What's the use? What do laravel read? What's the use? Apr 18, 2025 pm 12:09 PM

Laravel is a PHP development framework for quickly building web applications. Newbie people should start from the official documentation and gradually learn the core concepts of Laravel, such as routing, controller, model and views. Secondly, understand the basics of PHP, database, front-end technology and object-oriented programming. Learn in practice, start with simple projects, and summarize experiences in errors. In addition, with the help of the power of the community, we can get help and share experience from resources such as Stack Overflow, and ultimately continue to learn and practice, becoming a Laravel master.

See all articles