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:
4. Development environment setup
First check your MySQL version in the computer service, and then Enter the maven repository
Because my own version is after 5.0, I chose 5.1.47, and the major versions must be consistent
Just download the jar. Remember, the jar package cannot be decompressed.
The next step is to put the idea in the root directory. Create a folder under and then import the jar package
// 加載JDBC驅動程序:反射,這樣調用初始化com.mysql.jdbc.Driver類,即將該類加載到JVM方法 區(qū),并執(zhí)行該類的靜態(tài)方法塊、靜態(tài)屬性。 Class.forName("com.mysql.jdbc.Driver"); // 創(chuàng)建數(shù)據(jù)庫連接 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://服務器地址:端口/數(shù)據(jù)庫名?參數(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)
//關閉結果集 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } //關閉命令 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } //關閉連接命令 if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } }2. Add informationFirst 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對象 DataSource dataSource = new MysqlDataSource(); //設置相關內容 //URL User password //向下轉型 訪問數(shù)據(jù)庫 協(xié)議名 ip地址 要訪問那個地址 ((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ù)庫連接.進行后續(xù)連接 //connect生命周期較短 Connection connection = dataSource.getConnection(); //3、拼裝SQL語句 int id = 1; String name = "曹操"; int class_id = 10; //?是一個占位符,可以把一個具體的變量的值替換到? String sql = "insert into text values(?,?,?)"; PreparedStatement statement = connection.prepareStatement(sql); //1 2 3相當與?的下標 statement.setInt(1,id); statement.setString(2,name); statement.setInt(3,class_id); System.out.println("statement:" + statement); //4、執(zhí)行SQL語句 int ret = statement.executeUpdate(); System.out.println("ret:" + ret); //5、關閉相關資源 //后創(chuàng)建的先釋放,順序不能錯 statement.close(); connection.close(); } }
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)建實列
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ù)庫連接
Connection connection = dataSource.getConnection();
//3,構造SQL語句
String sql ="select * from text";
PreparedStatement statement = connection.prepareStatement(sql);
//4,執(zhí)行SQL語句
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,關閉相關資源
resultSet.close();
statement.close();
connection.close();
}
}
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("請輸入要刪除學生的姓名:");
String name = scanner.next();
//1,創(chuàng)建實列
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ù)庫連接
Connection connection = dataSource.getConnection();
//3,構造SQL語句
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,關閉資源
statement.close();
connection.close();
}
}
##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("請輸入學生的id:"); int id = scanner.nextInt(); System.out.println("請輸入修改學生姓名:"); String name = scanner.next(); //1,創(chuàng)建實列 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ù)庫連接 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,關閉資源 statement.close(); connection.close(); } }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

To achieve MySQL deployment automation, the key is to use Terraform to define resources, Ansible management configuration, Git for version control, and strengthen security and permission management. 1. Use Terraform to define MySQL instances, such as the version, type, access control and other resource attributes of AWSRDS; 2. Use AnsiblePlaybook to realize detailed configurations such as database user creation, permission settings, etc.; 3. All configuration files are included in Git management, support change tracking and collaborative development; 4. Avoid hard-coded sensitive information, use Vault or AnsibleVault to manage passwords, and set access control and minimum permission principles.

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

To collect user behavior data, you need to record browsing, search, purchase and other information into the database through PHP, and clean and analyze it to explore interest preferences; 2. The selection of recommendation algorithms should be determined based on data characteristics: based on content, collaborative filtering, rules or mixed recommendations; 3. Collaborative filtering can be implemented in PHP to calculate user cosine similarity, select K nearest neighbors, weighted prediction scores and recommend high-scoring products; 4. Performance evaluation uses accuracy, recall, F1 value and CTR, conversion rate and verify the effect through A/B tests; 5. Cold start problems can be alleviated through product attributes, user registration information, popular recommendations and expert evaluations; 6. Performance optimization methods include cached recommendation results, asynchronous processing, distributed computing and SQL query optimization, thereby improving recommendation efficiency and user experience.

Why do I need SSL/TLS encryption MySQL connection? Because unencrypted connections may cause sensitive data to be intercepted, enabling SSL/TLS can prevent man-in-the-middle attacks and meet compliance requirements; 2. How to configure SSL/TLS for MySQL? You need to generate a certificate and a private key, modify the configuration file to specify the ssl-ca, ssl-cert and ssl-key paths and restart the service; 3. How to force SSL when the client connects? Implemented by specifying REQUIRESSL or REQUIREX509 when creating a user; 4. Details that are easily overlooked in SSL configuration include certificate path permissions, certificate expiration issues, and client configuration requirements.

PHP plays the role of connector and brain center in intelligent customer service, responsible for connecting front-end input, database storage and external AI services; 2. When implementing it, it is necessary to build a multi-layer architecture: the front-end receives user messages, the PHP back-end preprocesses and routes requests, first matches the local knowledge base, and misses, call external AI services such as OpenAI or Dialogflow to obtain intelligent reply; 3. Session management is written to MySQL and other databases by PHP to ensure context continuity; 4. Integrated AI services need to use Guzzle to send HTTP requests, safely store APIKeys, and do a good job of error handling and response analysis; 5. Database design must include sessions, messages, knowledge bases, and user tables, reasonably build indexes, ensure security and performance, and support robot memory

When choosing a suitable PHP framework, you need to consider comprehensively according to project needs: Laravel is suitable for rapid development and provides EloquentORM and Blade template engines, which are convenient for database operation and dynamic form rendering; Symfony is more flexible and suitable for complex systems; CodeIgniter is lightweight and suitable for simple applications with high performance requirements. 2. To ensure the accuracy of AI models, we need to start with high-quality data training, reasonable selection of evaluation indicators (such as accuracy, recall, F1 value), regular performance evaluation and model tuning, and ensure code quality through unit testing and integration testing, while continuously monitoring the input data to prevent data drift. 3. Many measures are required to protect user privacy: encrypt and store sensitive data (such as AES

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction
