当前位置:网站首页>Younger sister Juan takes you to learn JDBC - 2-day dash Day1
Younger sister Juan takes you to learn JDBC - 2-day dash Day1
2022-06-29 17:25:00 【Hua Weiyun】
Blog home page : The blog home page of Beijing and JIUPU
Welcome to pay attention to the likes and comments
Reference Online Course : Power nodes
Starting time :2022 year 6 month 17 Japan
You do march and April , There will be an answer in August and September , Come on
If you think the blogger's article is good , Please support the blogger for the third company
Last words , The author is a newcomer , Not doing well in many ways , Welcome the boss to correct , Study together , To rush
1、JDBC What is it? ?Java DataBase Connectivity(Java Language connection database )
2、JDBC What is the essence of ?JDBC yes SUN A set of interfaces developed by the company (interface)java.sql.*; ( There are many interfaces in this package .)
Interfaces have callers and implementers . Interface oriented call 、 Interface oriented writing implementation classes , This is all interface oriented programming .
Why interface oriented programming ? Decoupling : Reduce program coupling , Improve the expansion of the program . Polymorphic mechanism is very typical : Abstract oriented programming .( Don't program for specific purposes ) Suggest :Animal a = new Cat();Animal a = new Dog();// Feeding methods public void feed(Animal a){ // Parent oriented programming .
} Don't suggest :Dog d = new Dog();Cat c = new Cat();
reflection : Why? SUN Develop a set JDBC The interface ? Because the underlying implementation principle of each database is different .Oracle Database has its own principle .MySQL Database also has its own principle .MS SqlServer Database also has its own principle .… Each database product has its own unique implementation principle .
JDBC What's the essence of ? A set of interfaces .
3、JDBC Preparation before development , Download the corresponding driver from the official website first jar package , Then configure it to an environment variable classpath among .
classpath=.;D:\course\06-JDBC\resources\MySql Connector Java 5.1.23\mysql-connector-java-5.1.23-bin.jar
The above configuration is developed in the way of text editor , Use IDEA When it comes to tools , There is no need to configure the above environment variables .IDEA It has its own configuration .
4、JDBC Six steps to programming ( I need to recite )
First step : Registration drive ( effect : tell Java Program , Which brand database will be connected soon )
The second step : Get the connection ( Express JVM The channel between the database process and the database process is opened , This belongs to communication between processes , A heavyweight , Be sure to close the channel after use .)
The third step : Get database operation object ( Special execution sql Object of statement )
Step four : perform SQL sentence (DQL DML…)
Step five : Process query result set ( Only if the fourth step is select At the time of statement , The fifth step is to process the query result set .)
Step six : Release resources ( Be sure to close the resource after using it .Java And database belong to the communication between processes , Be sure to turn it off after you turn it on .)
/*JDBC Six steps to programming */import java.sql.Driver;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Connection;import java.sql.Statement;
public class JDBCTest01{public static void main(String[] args){Connection conn = null;Statement stmt = null;try{//1、 Registration drive Driver driver = new com.mysql.jdbc.Driver(); // polymorphic , A parent type reference points to a child type object .// Driver driver = new oracle.jdbc.driver.OracleDriver(); // oracle The driver .DriverManager.registerDriver(driver);//2、 Get the connection /*url: Uniform resource locator ( The absolute path of a resource in the network )https://www.baidu.com/ This is it. URL.URL Which parts are included ? agreement IPPORT Resource name
http://182.61.200.7:80/index.html http:// Communication protocol 182.61.200.7 The server IP Address 80 The port of the software on the server index.html Is the name of a resource on the server jdbc:mysql://127.0.0.1:3306/bjpowernodejdbc:mysql:// agreement 127.0.0.1 IP Address 3306 mysql Database port number bjpowernode Specific database instance name .
explain :localhost and 127.0.0.1 It's all local IP Address . jdbc:mysql://192.168.151.27:3306/bjpowernode What is communication protocol , What's the usage? ? Communication protocol is the data transmission format set in advance before communication . How to transfer data packets , The format is set in advance . oracle Of URL: jdbc:oracle:thin:@localhost:1521:orcl */ String url = "jdbc:mysql://192.168.151.9:3306/bjpowernode"; String user = "root"; String password = "981127"; conn = DriverManager.getConnection(url,user,password); // [email protected] System.out.println(" Database connection object = " + conn); //3、 Get database operation object (Statement Special execution sql Of the statement ) stmt = conn.createStatement(); //4、 perform sql String sql = "insert into dept(deptno,dname,loc) values(50,' The personnel department ',' Beijing ')"; // Special execution DML Of the statement (insert delete update) // The return value is “ Affect the number of records in the database ” int count = stmt.executeUpdate(sql); System.out.println(count == 1 ? " Saved successfully " : " Save failed "); //5、 Process query result set }catch(SQLException e){ e.printStackTrace(); }finally{ //6、 Release resources // In order to ensure the release of resources , stay finally Close the resource in the statement block // And it should be closed from small to large // The results were analyzed respectively try..catch try{ if(stmt != null){ stmt.close(); } }catch(SQLException e){ e.printStackTrace(); } try{ if(conn != null){ conn.close(); } }catch(SQLException e){ e.printStackTrace(); } }}}
/* Another way to register drivers ( This way is often used )/import java.sql.;
public class JDBCTest03{public static void main(String[] args){try{//1、 Registration drive // This is the first way to write a registration driver .// DriverManager.registerDriver(new com.mysql.jdbc.Driver());// The second way to register drivers : frequently-used .// Why is this method often used ? Because the parameter is a string , The string can be written to xxx.properties In file .// The following method does not need to receive the return value , Because we just want to load actions with its classes .Class.forName("com.mysql.jdbc.Driver");//2、 Get the connection Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");// [email protected]System.out.println(conn);
}catch(SQLException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); }}}
// Configure all the information connected to the database into the configuration file /* In actual development, it is not recommended to write the information connecting to the database to java In the program ./import java.sql.;import java.util.*;
public class JDBCTest04{public static void main(String[] args){
// Use the resource binder to bind the property profile ResourceBundle bundle = ResourceBundle.getBundle("jdbc"); String driver = bundle.getString("driver"); String url = bundle.getString("url"); String user = bundle.getString("user"); String password = bundle.getString("password"); Connection conn = null; Statement stmt = null; try{ //1、 Registration drive Class.forName(driver); //2、 Get the connection conn = DriverManager.getConnection(url,user,password); //3、 Get database operation object stmt = conn.createStatement(); //4、 perform SQL sentence String sql = "update dept set dname = ' The sales department 2', loc = ' tianjin 2' where deptno = 20"; int count = stmt.executeUpdate(sql); System.out.println(count == 1 ? " Modification successful " : " Modification failed "); }catch(Exception e){ e.printStackTrace(); }finally{ //6、 Release resources if(stmt != null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } }}}
/* Process query result set ( Traversal result set .)/import java.sql.;
public class JDBCTest05{public static void main(String[] args){Connection conn = null;Statement stmt = null;ResultSet rs = null;try{//1、 Registration drive Class.forName("com.mysql.jdbc.Driver");//2、 Get the connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");//3、 Get database operation object stmt = conn.createStatement();//4、 perform sqlString sql = "select empno as a,ename,sal from emp";// int executeUpdate(insert/delete/update)// ResultSet executeQuery(select)rs = stmt.executeQuery(sql); // Special execution DQL Method of statement .//5、 Process query result set /*boolean flag1 = rs.next();//System.out.println(flag1); // trueif(flag1){// The line pointed to by the cursor has data // Take the data // getString() The characteristic of the method is : No matter what the data type in the database is , Are subject to String Take out in the form of .String empno = rs.getString(1); // JDBC All subscripts in are from 1 Start . Not from 0 Start .String ename = rs.getString(2);String sal = rs.getString(3);System.out.println(empno + "," + ename + "," + sal);}
flag1 = rs.next(); if(flag1){ // Of the following procedure 1 2 3 Which column did you say . String empno = rs.getString(1); String ename = rs.getString(2); String sal = rs.getString(3); System.out.println(empno + "," + ename + "," + sal); } */ while(rs.next()){ /* String empno = rs.getString(1); String ename = rs.getString(2); String sal = rs.getString(3); System.out.println(empno + "," + ename + "," + sal); */ /* // This is not obtained by subscript of column , Get... With the name of the column //String empno = rs.getString("empno"); String empno = rs.getString("a"); // Focus on : The column name is not a column name in the table , Is the column name of the query result set . String ename = rs.getString("ename"); String sal = rs.getString("sal"); System.out.println(empno + "," + ename + "," + sal); */ // In addition to String Type out , You can also take out... In a specific type . /* int empno = rs.getInt(1); String ename = rs.getString(2); double sal = rs.getDouble(3); System.out.println(empno + "," + ename + "," + (sal + 100)); */ int empno = rs.getInt("a"); String ename = rs.getString("ename"); double sal = rs.getDouble("sal"); System.out.println(empno + "," + ename + "," + (sal + 200)); } }catch(Exception e){ e.printStackTrace(); }finally{ //6、 Release resources if(rs != null){ try{ rs.close(); }catch(Exception e){ e.printStackTrace(); } } if(stmt != null){ try{ stmt.close(); }catch(Exception e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(Exception e){ e.printStackTrace(); } } }}}
//6、 Release resources if(rs != null){try{rs.close();}catch(Exception e){e.printStackTrace();}}if(stmt != null){try{stmt.close();}catch(Exception e){e.printStackTrace();}}if(conn != null){try{conn.close();}catch(Exception e){e.printStackTrace();}}}}
边栏推荐
- NAACL 2022 | 机器翻译SOTA模型的蒸馏
- Kali installation tutorial 2020
- 卷妹带你学数据库---5天冲刺Day4
- Leetcode daily question - 535 Encryption and decryption of tinyurl
- MySQL触发器如何创建与删除
- Sectigo ov pan domain name certificate is 1590 yuan a year easy to use
- 在供应链场景应用中,供应链管理系统扮演什么角色?
- C语言练习----指针字符串、链表
- The fixed assets management system enables enterprises to dynamically master assets
- windows平台下的mysql启动等基本操作
猜你喜欢

LeetCode 每日一题——535. TinyURL 的加密与解密

为什么信息化 ≠ 数字化?终于有人讲明白了

微信小程序开发储备知识

mysql在linux中2003错误如何解决

Subgraphs in slam

Tencent cloud released orbit, an automated delivery and operation and maintenance product, to promote enterprise applications to be fully cloud native

0基础自学STM32(野火)——使用寄存器点亮LED——GPIO功能框图讲解

mysql支持外键吗

mysql数据库扫盲,你真的知道什么是数据库嘛

LSB hidden items of stream carrier based on assembly implementation
随机推荐
Li Kou today's question -535 Encryption and decryption of tinyurl
线段树、树状数组模板(复制粘贴确实好用)
mysql支持外键吗
0 basic self-study STM32 (wildfire) -- use register to light LED -- Explanation of GPIO function block diagram
“授权同意”落地压力大?隐私计算提供一种可能的合规“技术解”
Kali installation tutorial 2020
从居家办公中感悟适配器模式 | 社区征文
OpenFeign使用步骤 轮询策略与权重 log4j使用 openFeign拦截器的配置
【R语言数据科学】:文本挖掘(以特朗普推文数据为例)
反射
@Component与@Configuration区别
MySQL highly available cluster – MHA
基于汇编实现的流载体的LSB隐藏项目
Which is better and safer, GF e-gold or Dongfang fortune
基于C语言开发实现的一个用户级线程库
如何创建虚拟形象
卷妹带你学jdbc—2天冲刺Day1
0基础自学STM32(野火)——使用寄存器点亮LED——GPIO功能框图讲解
What role does the supply chain management system play in the supply chain scenario?
R语言使用glm函数构建泊松对数线性回归模型处理三维列联表数据构建饱和模型、使用exp函数和coef函数获取模型所有变量的事件密度比(Incidence Density Ratio,IDR)并解读