


How to use MySQL for JDBC programming and addition, deletion, modification and query
Java database programming JDBC
Concept
JDBC is a Java API used to execute sql statements. It is the database connection specification in java. This API consists of some interfaces and classes. It provides a standard API that allows Java developers to uniformly access multiple relational databases
The essence is to implement a MySQL client through code and interact with data through the network and server. , the client cannot appear out of thin air, so the database provides a set of APIs to facilitate our implementation
There are many types of databases, and the APIs provided by different databases are different, so java is used to solve this problem One question provides JDBC, a database operation API that comes with java. This API covers all database operation modes.
Essentially, java itself completes the JDBC API and database API. Convert between
Use steps
to create a DataSource object. This object describes where the database server is.
DataSource dataSource = new MysqlDataSource(); //设置数据库所在的地址 ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/lmp?characterEncoding=utf8&useSSL=false"); //设置登录数据库的用户名 ((MysqlDataSource)dataSource).setUser("root"); //设置登录数据库的密码 ((MysqlDataSource)dataSource).setPassword("woshizhu123");
Connect to the database through Connection (enter the password to connect successfully)
//import java.sql.Connection; Connection connection = dataSource.getConnection();
Splice the sql statement (write the sql statement)
String sql = "insert into student values(1,'张三')";
Pack the sql statement into an object
PreparedStatement statement = connection.prepareStatement(sql);
Execute sql statement (press Enter to execute the sql statement)
int ret = statement.executeUpdate();
Execute update delete insert Use executeUpdate() method
Execute select Use executeQuery( ) Method
Using the executeQuery() method will return a resultSet collection, including the found data. Initially, the resultSet does not point to any row of records. Use next to point it to the first record. record, and then use next to point to the next record
Release resources
statement.close(); connection.close();
Use JDBC to implement addition (insert)
public class TestJDBC { public static void main(String[] args) throws SQLException { Scanner scanner = new Scanner(System.in); DataSource dataSource = new MysqlDataSource(); ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf-8&useSSL=false"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("woshizhu123"); Connection connection = dataSource.getConnection(); System.out.println("输入id"); int id = scanner.nextInt(); System.out.println("输入名字"); String name = scanner.next(); String sql = "insert into student values(?,?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1,id); statement.setString(2,name); int ret = statement.executeUpdate(); if(ret == 1){ System.out.println("插入成功"); }else { System.out.println("插入失败"); } statement.close(); connection.close(); } }
Use JDBC to implement deletion (delete) )
public class TestJDBCDelete { public static void main(String[] args) throws SQLException { DataSource dataSource = new MysqlDataSource(); ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("woshizhu123"); Connection connection = dataSource.getConnection(); Scanner scanner = new Scanner(System.in); System.out.println("请输入要删除的id"); int id = scanner.nextInt(); String sql = "delete from student where id = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,id); int ret = preparedStatement.executeUpdate(); System.out.println(ret); preparedStatement.close(); connection.close(); }
Use JDBC to implement modification (update)
public class TestJDBCUpdate { public static void main(String[] args) throws SQLException { DataSource dataSource = new MysqlDataSource(); ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("woshizhu123"); Connection connection = dataSource.getConnection(); Scanner scanner = new Scanner(System.in); System.out.println("请输入要修改的学生id"); int id = scanner.nextInt(); System.out.println("请输入要修改的学生姓名"); String name = scanner.next(); String sql = "update student set name = ? where id = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1,name); statement.setInt(2,id); int ret = statement.executeUpdate(); System.out.println(ret); statement.close(); connection.close(); } }
Use JDBC to implement search (select)
public static void testJDBCSelect() throws SQLException { //1创建DataSource对象 DataSource dataSource = new MysqlDataSource(); //2连接数据库 ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_5_31?characterEncoding=utf-8&useSSL=true"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("listen"); Connection connection = dataSource.getConnection(); //3拼接sql String sql = "select * from student"; PreparedStatement statement = connection.prepareStatement(sql); //4执行sql ResultSet resultSet = statement.executeQuery(); //5遍历得到的集合 while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int classId = resultSet.getInt("classId"); System.out.println("id " + id + " name " + name + " classId " + classId); } //6关闭资源 resultSet.close(); statement.close(); connection.close(); }
The above is the detailed content of How to use MySQL for JDBC programming and addition, deletion, modification and query. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.
