当前位置:网站首页>MySQL JDBC programming
MySQL JDBC programming
2022-07-04 04:37:00 【Lockey-s】
Blog home page :Lockey-s Welcome to thumb up Collection Leaving a message. Welcome to discuss ! This paper is written by 【Lockey-s】 original ! First appeared in CSDN Because the blogger is learning Xiaobai one , There are bound to be mistakes , If you have any questions, please leave a message in the comment area to point out , Thank you no all ! Boutique column ( Update from time to time )
JDBC Programming
Concept
JDBC Is a kind and method , It's a kind of execution SQL Of the statement Java API, It can realize unified access to a variety of databases , It's like the monitor agreeing on the statistical format of the data . The advantage is that the portability of the program is greatly enhanced , Not limited to specific database vendors API.
Use
Introduce dependencies
Introducing dependencies requires MySQL Driver package ( hold MySQL Self api To convert into JDBC style ).
Download the driver package
The best way is to MySQL Official website , however MySQL By Oracle After the acquisition , It's hard to find , So you can go maven The central warehouse To install , And then the search MySQL, The first result is :
Then click in to choose 5.1.x Series is OK , Because of my MySQL yes 5.7 Series of , So it uses 5 Series of , If MySQL yes 8 Series of , Then use 8 Series of , Be sure to communicate with your MySQL Version match , If it doesn't match , May lead to bug :
Then click the previous version number , Then enter the page :
Then order that jar Button , Will download the driver package ,jar It's written by others class file .
Import into project
- After entering the project , You can create a directory , What's created here is lib
- Just download jar Copy the file to the directory just now , Directly copy the file and click lib, Then paste it
- Right click the directory just now , There is one add as library Then click this option , That's what makes jar The package is introduced into the project , Items will be read jar Inside .class file . Otherwise the code will not find jar There are some classes .
Write code
JDBC Basic process of insertion
establish DataSource object
This object describes where the database server is . The code is as follows :
DataSource dataSource = new MysqlDataSource();
among DataSource yes JDBC The interface with , hinder MysqlDataSource From previously downloaded jar package , It is an upward transformation .
Set the database address : The database address here can be copied directly ,127.0.0.1 Indicating the machine IP ,3306 It's the port number ,user It's the database name , Followed by the character set ,SSL Is whether the transmission process is encrypted .
((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/user?characterEncoding=utf8&useSSL=false");
Set the database user name :
((MysqlDataSource) dataSource).setUser();
Set the password of the database :
((MysqlDataSource) dataSource).setPassword();
It can also be written like this , In this way, there is no transformation :
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setURL();
dataSource.setUser();
dataSource.setPassword();
Because the instance held in our code is DataSource type , If other codes need to be used later DataSource , Relevant parameters are also DataSource, The code hardly needs to be changed , Namely “ Low coupling ”.
Establish a connection with the database server
adopt dataSource.Connection To establish a connection :
Connection connection = dataSource.getConnection();
It should be noted that , It uses java.sql Inside Connection:
Operating the database
- When operating the database , The key is to construct a SQL sentence , structure String Class , Don't write a semicolon :
String sql = "insert into student values(1,' Zhang San ')";
- And then through Connection Inside prepareStatement Method , hold String Style sql The sentence is translated into JDBC The object in it :
PreparedStatement statement = connection.prepareStatement(sql);
- perform sql , If it is inserted , Namely executeUpdate, If you choose , Namely executeQuery:
int line = statement.executeUpdate();
there line Is the return value , Just a few lines were affected .
- Release resources , Create first and release later , After the creation of the first release .
statement.close();
connection.close();
Execute code , The return value is 1, It means that one line has been affected :
After three executions , Return to the database to view the contents , Found three more records :
The user enters the content to insert
adopt Scanner To let users input :
int id = scanner.nextInt();
String name = scanner.next();
After user input , hold id, and name Replace the sql Statement inside , stay sql sentence Of values In the middle ? Instead of :
String sql1 = "insert into student values(?,?)";
these two items. ? It means that the value of the current field has not been determined , Take a seat first , Reuse PreparedStatement Of setXXX Replace with a series of methods :
PreparedStatement statement1 = connection.prepareStatement(sql1);
statement1.setInt(1,id);
statement1.setString(2,name);
there 1,2 It's the subscript , from 1 Start calculating , Take the first one. ? Replace with id Value , Put the second one ? Replace with name Value . Then print the replacement object :
System.out.println("statement1" + statement1);
Assembled SQL The output value of is below :
In the database lisi Also successfully inserted .
JDBC Basic process of deletion
- create data source :
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/user?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("");
- Establishing a connection :
Connection connection = dataSource.getConnection();
- User input id:
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
- assemble sql sentence :
String sql = "delete from student where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
- perform sql :
int line = statement.executeUpdate();
System.out.println(line);
- Recycle resources :
statement.close();
connection.close();
The operation results are as follows :
The database data is as follows :
You can see id by 1 All of them have been deleted .
JDBC The basic process of updating
- create data source :
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/user?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("");
- Establishing a connection
Connection connection = dataSource.getConnection();
- User input id
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
String name = scanner.next();
- assemble sql sentence
String sql = "update student set name = ? where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setInt(2, id);
System.out.println("statement" + statement);
- perform sql
int line = statement.executeUpdate();
System.out.println("line" + line);
- Recycle resources
statement.close();
connection.close();
In the database id be equal to 2 The name of is :lisi
The results are as follows :
You can see that the data in the database has also been modified :
JDBC Basic process of searching
- create data source :
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/user?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("");
- Establishing a connection
Connection connection = dataSource.getConnection();
- assemble sql sentence
String sql = "select * from student order by id";
PreparedStatement statement = connection.prepareStatement(sql);
- perform sql, Because the query operation returns a temporary table , So use executeQuery, The returned temporary table is used ResultSet To express .
ResultSet resultSet = statement.executeQuery();
- Traverse the result set , That is, traverse the returned temporary table , Get each returned row first , Then get every column of this result .
while (resultSet.next()) {
// First, get the columns for one row
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("id= " + id + " ,name= " + name);
}
- close resource
resultSet.close();
statement.close();
connection.close();
The database resources are as follows :
Code execution result ( Press id Sequential arrangement ) as follows :
边栏推荐
- ModStartBlog 现代化个人博客系统 v5.2.0 源码下载
- Y55. Chapter III kubernetes from entry to proficiency -- HPA controller and metrics server (28)
- What is context?
- 旭化成首次参展第五届中国国际进口博览会(5th CIIE)
- 十字路口通行优先权,十字路口通行规则图解
- leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机(简单)
- Redis:有序集合zset类型数据操作命令
- 架构训练毕业设计+总结
- Kivy tutorial custom fonts (tutorial with source code)
- (pointeur) Écrivez - vous une fonction qui compare la taille de la chaîne et fonctionne comme strcmp.
猜你喜欢
Architecture training graduation design + summary
What is context?
什么是上下文?
A beautiful API document generation tool
Tcp- simple understanding of three handshakes and four waves
Longest increasing subsequence problem (do you really know it)
统计遗传学:第三章,群体遗传
Redis:集合Set类型数据的操作命令
Boutique website navigation theme whole station source code WordPress template adaptive mobile terminal
苹果CMS仿西瓜视频大气响应式视频模板源码
随机推荐
PaddleHub人脸识别方案部署,将训练好的模型在pytchrom中进行部署应用
Tcp- simple understanding of three handshakes and four waves
Detailed explanation of event cycle
【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
Wobo Union ended its strategic evaluation and decided to retain Bozi's business with excellent performance
十字路口通行优先权,十字路口通行规则图解
Unity资源路径
Application scheme of Puyuan ds1000z series digital oscilloscope in communication principle experiment
Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?
RPC Technology
Redis:哈希hash类型数据操作命令
仿《游戏鸟》源码 手游发号评测开服开测合集专区游戏下载网站模板
Senior developers tell you, how to write excellent code?
ModStartBlog 现代化个人博客系统 v5.2.0 源码下载
Operation of ES6
【愚公系列】2022年7月 Go教学课程 001-Go语言前提简介
Precautions for accompanying driving these 23 points should be paid attention to!
微信脑力比拼答题小程序_支持流量主带最新题库文件
[Yugong series] go teaching course 001 in July 2022 - Introduction to go language premise
How to add custom API objects in kubernetes (1)