国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. Necessary conditions for database programming
2. Java database programming: JDBC
3. Working Principle of JDBC
4. Development environment setup
%%PRE_BLOCK_10%%
Home Database Mysql Tutorial How to analyze JDBC programming in MySQL

How to analyze JDBC programming in MySQL

May 30, 2023 pm 10:19 PM
mysql jdbc

1. Necessary conditions for database programming

Programming languages, such as Java, C, C, Python and other databases, such as Oracle, MySQL, SQL Server and other database driver packages: different databases correspond to different Programming languages ??provide different database driver packages. For example, MySQL provides the Java driver package mysql-connector-java. This driver package is required to operate MySQL based on Java. If you want to use Java to operate the Oracle database, you must use Oracle's database driver package ojdbc.

2. Java database programming: JDBC

Java Database Connectivity, referred to as JDBC, is a Java API used to connect to a database. Java API is used to execute SQL statements, which is a database connection specification in Java. This API consists of some classes and interfaces in the java.sql.*, javax.sql.* packages. It provides a standard API for Java developers to operate databases and can provide unified access to multiple relational databases.

3. Working Principle of JDBC

DBC provides a unified access method for a variety of relational databases. As a high-level abstraction for a specific manufacturer's database access API, it mainly includes some common interface classes.

JDBC access database hierarchy:

How to analyze JDBC programming in MySQL

4. Development environment setup

First check your MySQL version in the computer service, and then Enter the maven repository

How to analyze JDBC programming in MySQL

How to analyze JDBC programming in MySQL

Because my own version is after 5.0, I chose 5.1.47, and the major versions must be consistent

How to analyze JDBC programming in MySQL

Just download the jar. Remember, the jar package cannot be decompressed.

How to analyze JDBC programming in MySQL

The next step is to put the idea in the root directory. Create a folder under and then import the jar package

How to analyze JDBC programming in MySQL

How to analyze JDBC programming in MySQL

How to analyze JDBC programming in MySQL

How to analyze JDBC programming in MySQL

# # If there is no error and it continues to be OK, there will be no problem, indicating that the import is successful

5. JDBC programming in MySQL

1. Five-step process

Establishing a database connection

// 加載JDBC驅(qū)動(dòng)程序:反射,這樣調(diào)用初始化com.mysql.jdbc.Driver類,即將該類加載到JVM方法
區(qū),并執(zhí)行該類的靜態(tài)方法塊、靜態(tài)屬性。
Class.forName("com.mysql.jdbc.Driver");
// 創(chuàng)建數(shù)據(jù)庫(kù)連接
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test?
user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
//MySQL數(shù)據(jù)連接的URL參數(shù)格式如下:
jdbc:mysql://服務(wù)器地址:端口/數(shù)據(jù)庫(kù)名?參數(shù)名=參數(shù)值

Create operation command (Statement)

Statement statement = connection.createStatement();

Execute SQL statement

ResultSet resultSet= statement.executeQuery(
                "select id, sn, name, qq_mail, classes_id from student");

Process the result set

while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String sn = resultSet.getString("sn");
            String name = resultSet.getString("name");
            int classesId = resultSet.getInt("classes_id");
            System.out.println(String.format("Student: id=%d, sn=%s, name=%s, 
classesId=%s", id, sn, name, classesId));
       }

Release resources (close result set, command, connection)

//關(guān)閉結(jié)果集
if (resultSet != null) {
    try {
        resultSet.close();
   } catch (SQLException e) {
        e.printStackTrace();
   }
}
//關(guān)閉命令
if (statement != null) {
    try {
        statement.close();
   } catch (SQLException e) {
        e.printStackTrace();
   }
}
//關(guān)閉連接命令
if (connection != null) {
    try {
        connection.close();
   } catch (SQLException e) {
        e.printStackTrace();
   }
}

2. Add information

First create a database and create a table

 create database java122;
 create table text(id int,name varchar(5),class_id int);
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
 
public class TextJDBC {
    //DataSource
    //Connection
    //PrepareStatement
 
 
    public static void main(String[] args) throws SQLException{
        //1、創(chuàng)建DataSource對(duì)象
         DataSource dataSource = new MysqlDataSource();
        //設(shè)置相關(guān)內(nèi)容
        //URL User password
        //向下轉(zhuǎn)型                     訪問(wèn)數(shù)據(jù)庫(kù)   協(xié)議名        ip地址 要訪問(wèn)那個(gè)地址
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java122?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("180210");
        
        //2、和數(shù)據(jù)庫(kù)連接.進(jìn)行后續(xù)連接
        //connect生命周期較短
        Connection connection = dataSource.getConnection();
        
        //3、拼裝SQL語(yǔ)句
        int id = 1;
        String name = "曹操";
        int class_id = 10;
        //?是一個(gè)占位符,可以把一個(gè)具體的變量的值替換到?
        String sql = "insert into text values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        //1 2 3相當(dāng)與?的下標(biāo)
        statement.setInt(1,id);
        statement.setString(2,name);
        statement.setInt(3,class_id);
        System.out.println("statement:" + statement);
 
        //4、執(zhí)行SQL語(yǔ)句
        int ret = statement.executeUpdate();
        System.out.println("ret:" + ret);
 
        //5、關(guān)閉相關(guān)資源
        //后創(chuàng)建的先釋放,順序不能錯(cuò)
        statement.close();
        connection.close();
 
    }
}

How to analyze JDBC programming in MySQL

3. Query information

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
 
import javax.sql.DataSource;
import javax.xml.transform.Source;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
 
public class Text1 {
 
 
    public static void main(String[] args) throws SQLException {
 
        //1,創(chuàng)建實(shí)列
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java122?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("180210");
 
        //2,數(shù)據(jù)庫(kù)連接
        Connection connection = dataSource.getConnection();
 
        //3,構(gòu)造SQL語(yǔ)句
 
        String sql ="select * from text";
        PreparedStatement statement = connection.prepareStatement(sql);
 
        //4,執(zhí)行SQL語(yǔ)句
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int class_id = resultSet.getInt("class_id");
            System.out.println("id: " + id  + "name: " + name  + "class_id: " + class_id);
        }
 
        //5,關(guān)閉相關(guān)資源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

How to analyze JDBC programming in MySQL

4. Delete information

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
 
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
 
public class Textur2 {
 
 
    public static void main(String[] args) throws SQLException {
 
 
        Scanner scanner = new Scanner(System.in);
        System.out.println("請(qǐng)輸入要?jiǎng)h除學(xué)生的姓名:");
        String name = scanner.next();
        //1,創(chuàng)建實(shí)列
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java122?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("180210");
 
        //2,數(shù)據(jù)庫(kù)連接
        Connection connection = dataSource.getConnection();
 
        //3,構(gòu)造SQL語(yǔ)句
        String sql = "delete from text where name = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);
 
        //4,執(zhí)行SQL
        int ret = statement.executeUpdate();
        if (ret == 1){
            System.out.println("刪除成功");
        }else {
            System.out.println("刪除失敗");
        }
 
        //5,關(guān)閉資源
        statement.close();
        connection.close();
 
 
    }
}

How to analyze JDBC programming in MySQL

How to analyze JDBC programming in MySQL##5. Modify information

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
 
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
 
public class Text4 {
 
 
    public static void main(String[] args) throws SQLException {
 
 
        //修改信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("請(qǐng)輸入學(xué)生的id:");
        int id = scanner.nextInt();
        System.out.println("請(qǐng)輸入修改學(xué)生姓名:");
        String name = scanner.next();
 
        //1,創(chuàng)建實(shí)列
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java122?characterEncoding=utf-8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("180210");
 
        //2,數(shù)據(jù)庫(kù)連接
        Connection connection = dataSource.getConnection();
 
        //3,拼裝SQL
        String sql = "update text set name = ? where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);
        statement.setInt(2,id);
        //4,執(zhí)行SQL
        int set = statement.executeUpdate();
        if (set == 1){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失敗");
        }
 
        //5,關(guān)閉資源
        statement.close();
        connection.close();
    }
}

How to analyze JDBC programming in MySQL

The above is the detailed content of How to analyze JDBC programming in 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Establishing secure remote connections to a MySQL server Establishing secure remote connections to a MySQL server Jul 04, 2025 am 01:44 AM

TosecurelyconnecttoaremoteMySQLserver,useSSHtunneling,configureMySQLforremoteaccess,setfirewallrules,andconsiderSSLencryption.First,establishanSSHtunnelwithssh-L3307:localhost:3306user@remote-server-Nandconnectviamysql-h127.0.0.1-P3307.Second,editMyS

Performing logical backups using mysqldump in MySQL Performing logical backups using mysqldump in MySQL Jul 06, 2025 am 02:55 AM

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

Handling NULL Values in MySQL Columns and Queries Handling NULL Values in MySQL Columns and Queries Jul 05, 2025 am 02:46 AM

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

Analyzing the MySQL Slow Query Log to Find Performance Bottlenecks Analyzing the MySQL Slow Query Log to Find Performance Bottlenecks Jul 04, 2025 am 02:46 AM

Turn on MySQL slow query logs and analyze locationable performance issues. 1. Edit the configuration file or dynamically set slow_query_log and long_query_time; 2. The log contains key fields such as Query_time, Lock_time, Rows_examined to assist in judging efficiency bottlenecks; 3. Use mysqldumpslow or pt-query-digest tools to efficiently analyze logs; 4. Optimization suggestions include adding indexes, avoiding SELECT*, splitting complex queries, etc. For example, adding an index to user_id can significantly reduce the number of scanned rows and improve query efficiency.

Aggregating data with GROUP BY and HAVING clauses in MySQL Aggregating data with GROUP BY and HAVING clauses in MySQL Jul 05, 2025 am 02:42 AM

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

Managing Transactions and Locking Behavior in MySQL Managing Transactions and Locking Behavior in MySQL Jul 04, 2025 am 02:24 AM

MySQL transactions and lock mechanisms are key to concurrent control and performance tuning. 1. When using transactions, be sure to explicitly turn on and keep the transactions short to avoid resource occupation and undolog bloating due to long transactions; 2. Locking operations include shared locks and exclusive locks, SELECT...FORUPDATE plus X locks, SELECT...LOCKINSHAREMODE plus S locks, write operations automatically locks, and indexes should be used to reduce the lock granularity; 3. The isolation level is repetitively readable by default, suitable for most scenarios, and modifications should be cautious; 4. Deadlock inspection can analyze the details of the latest deadlock through the SHOWENGINEINNODBSTATUS command, and the optimization methods include unified execution order, increase indexes, and introduce queue systems.

Paginating Results with LIMIT and OFFSET in MySQL Paginating Results with LIMIT and OFFSET in MySQL Jul 05, 2025 am 02:41 AM

MySQL paging is commonly implemented using LIMIT and OFFSET, but its performance is poor under large data volume. 1. LIMIT controls the number of each page, OFFSET controls the starting position, and the syntax is LIMITNOFFSETM; 2. Performance problems are caused by excessive records and discarding OFFSET scans, resulting in low efficiency; 3. Optimization suggestions include using cursor paging, index acceleration, and lazy loading; 4. Cursor paging locates the starting point of the next page through the unique value of the last record of the previous page, avoiding OFFSET, which is suitable for "next page" operation, and is not suitable for random jumps.

Setting up asynchronous primary-replica replication in MySQL Setting up asynchronous primary-replica replication in MySQL Jul 06, 2025 am 02:52 AM

To set up asynchronous master-slave replication for MySQL, follow these steps: 1. Prepare the master server, enable binary logs and set a unique server-id, create a replication user and record the current log location; 2. Use mysqldump to back up the master library data and import it to the slave server; 3. Configure the server-id and relay-log of the slave server, use the CHANGEMASTER command to connect to the master library and start the replication thread; 4. Check for common problems, such as network, permissions, data consistency and self-increase conflicts, and monitor replication delays. Follow the steps above to ensure that the configuration is completed correctly.

See all articles