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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

What are the advantages of using MySQL over other relational databases? What are the advantages of using MySQL over other relational databases? May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How to analyze the execution plan of MySQL query How to analyze the execution plan of MySQL query Apr 29, 2025 pm 04:12 PM

Use the EXPLAIN command to analyze the execution plan of MySQL queries. 1. The EXPLAIN command displays the execution plan of the query to help find performance bottlenecks. 2. The execution plan includes fields such as id, select_type, table, type, possible_keys, key, key_len, ref, rows and Extra. 3. According to the execution plan, you can optimize queries by adding indexes, avoiding full table scans, optimizing JOIN operations, and using overlay indexes.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How to rename a database in MySQL How to rename a database in MySQL Apr 29, 2025 pm 04:00 PM

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

See all articles