当前位置:网站首页>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();}}}}
边栏推荐
- Use SSH to pull codes
- 0基础自学STM32(野火)——使用寄存器点亮LED——GPIO功能框图讲解
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
- Naacl 2022 | distillation of machinetranslation SOTA model
- What is the function of MySQL cursors
- XAMPP Apache安装时问题总结
- Automatic vending machine
- R语言将距离矩阵输入给hclust函数进行层次聚类分析,method参数指定两个组合数据点间的距离计算方式、plot函数可视化层次聚类的树状图(dendrogram)
- 力扣解法汇总535-TinyURL 的加密与解密
- R语言ggplot2可视化:使用patchwork包(直接使用加号+)将一个ggplot2可视化结果和一个plot函数可视化结果横向组合起来形成最终结果图
猜你喜欢
随机推荐
机器人不需要保养和出界也能拿金牌是一样一样的
Master slave replication of MySQL
[R language data science]: Text Mining (taking Trump's tweet data as an example)
2022年软件评测师考试大纲
The dplyr package filter function of R language filters the data in dataframe data through combinatorial logic (and logic). The content of one field is equal to one of the specified vectors, and the v
It is the same that robots can win gold medals without maintenance and out of bounds
mysql数据库扫盲,你真的知道什么是数据库嘛
R language uses GLM function to build Poisson logarithm linear regression model, processes three-dimensional contingency table data to build saturation model, uses exp function and coef function to ob
Error:Connection refused: connect
Mysql中锁的使用场景是什么
自学结构体(小甲鱼c语言)
controller、service、dao之间的关系
About Kali using xshell connection
Leetcode daily question - 535 Encryption and decryption of tinyurl
微信小程序开发储备知识
卷妹带你学jdbc—2天冲刺Day1
关于harbor私有仓库忘记登录密码
ICML 2022 | transferable imitation learning method based on decoupling gradient optimization
正则表达式
What role does the supply chain management system play in the supply chain scenario?








