当前位置:网站首页>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();}}}}
边栏推荐
- Function calculation asynchronous task capability introduction - task trigger de duplication
- Redis 原理 - Sorted Set (ZSet)
- Does MySQL support foreign keys
- PCB frame drawing - ad19
- mysql如何查询表的字符集编码
- [R language data science]: Text Mining (taking Trump's tweet data as an example)
- XAMPP Apache安装时问题总结
- 【Oracle】基础知识面试题
- mysql. What is the concept of sock
- c# 国内外ORM 框架 dapper efcore sqlsugar freesql hisql sqlserver数据常规插入测试性能对比
猜你喜欢

MySQL触发器如何创建与删除

A user level thread library based on C language

What are the project management systems suitable for small and medium-sized enterprises?

Viewing splitchunks code segmentation from MPX resource construction optimization

mysql. What is the concept of sock

Naacl 2022 | distillation of machinetranslation SOTA model

NAACL 2022 | 机器翻译SOTA模型的蒸馏

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

linux中mysql 1045错误如何解决

mysql.sock的概念是什么
随机推荐
Redis布隆过滤器和布谷鸟过滤器
InheritableThreadLocal 在线程池中进行父子线程间消息传递出现消息丢失的解析
R language uses user-defined functions to write deep learning linear activation functions and visualize linear activation functions
KUKA子程序/函数怎么建立和使用方法
R语言使用epiDisplay包的kap函数(kap.2.raters函数)计算Kappa统计量的值(总一致性、期望一致性)、对两个评分对象的结果进行一致性分析、评分的类别为多个类别
函数计算异步任务能力介绍 - 任务触发去重
Function calculation asynchronous task capability introduction - task trigger de duplication
Tencent cloud released orbit, an automated delivery and operation and maintenance product, to promote enterprise applications to be fully cloud native
An error is reported in the Flink SQL rownumber. Who has met him? How to solve it?
c# 国内外ORM 框架 dapper efcore sqlsugar freesql hisql sqlserver数据常规插入测试性能对比
2022年软件评测师考试大纲
自定义HandlerInterceptor拦截器实现用户鉴权
Understanding adapter mode from home office | community essay solicitation
基于C语言开发实现的一个用户级线程库
C语言练习----指针字符串、链表
在线文本数字识别列表求和工具
R语言dplyr包filter函数通过组合逻辑(与逻辑)过滤dataframe数据中的数据、其中一个字段的内容等于指定向量中的其中一个,并且另外一个字段值大于某一阈值
About harbor private warehouse forgetting the login password
深圳内推 | 深圳计算科学研究院招聘机器学习助理工程师(校招)
Development of freedom free agreement pledge mining system