day20191009jdbc study notes

Wednesday Wednesday

JDBC (Java DataBase Connectivity, java Database Connectivity) is a Java API to execute SQL statements used, can provide unified access to multiple relational database that consists of a set written in Java classes and interfaces. JDBC provides a benchmark that allow you to build more advanced tools and interfaces that enable database developers to write database applications. (JDBC is what?)

API, stands for Application Programming Interface, an application programming interface that is.
API is some pre-defined function, purpose is to provide the application developer the ability of a software or a hardware-based access to a set of routines, and without having to understand the details of accessing the source or the internal working mechanism.
API is the operating system to call interface, applications, application of the operating system to execute command application (action) by calling the operating system API. In Windows, the system API function calls are provided by way of.
SDA and API: API may be considered to be included in the SDK: SDK is a combination of a series of documents, including lib, dll, .h, documentation, samples; when API is an interface for the program, providing a user program, that is, a series of modular classes and functions.
API and GUI: both of which are direct user interface, except that the API interface is a kind of operating system or programming interface, but the GUI interface belongs to a graphical operating system.

JDBC_Chapter03_20191009 classroom content

  Notes    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

     1.JDBC: Java technology connecting a database;

     2. To use the JDBC database connection
          First, load the driver (Driver: database vendor, to distinguish different role management database identification)
          Second, the use DriverManager connection database (DriverManager: Management to connect different database driver)
          Third, create a PreparedStatement object, the establishment of database connection channel, execute transmission sql statement
          Fourth, access to the database ResultSet returned result set
          V. release resources
          PS: lib: specialized storage jar package

1.DAO mode components:
     Program ----> Database
     entity class database table
     tools: public database connections, closed, additions and deletions to the common query
     interfaces: Program promotion is oriented programming interface, thereby reducing the program coupling
     implementation class: implement different interfaces by different needs

2. the layered composition traditional Web application (MVC mode)
      M: model [persistent object (entity classes) + DAO (data access layer) + service (service access layer )]
      V: view the client displays the page (html, jsp, asp, php ...) ]
      C: control layer [Servlet, front and back data exchange relay station]

   Invoicing requirements    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

1 user login
2 Log (jsp data exchange JavaWeb of)
3 sale of
four pairs of sales records for paging query and sorted according to the date of sale (descending)
5 under the trade name query inventory quantity of the goods

  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -

File sale.sql

User table ##
the CREATE TABLE test`.`users` `(
` id` the INT (10) the AUTO_INCREMENT the COMMENT the NOT NULL 'user ID',
`username` VARCHAR (20 is) the COMMENT the NOT NULL 'username',
` password` VARCHAR ( 20) NOT NULL COMMENT 'password',
(20) NOT NULL COMMENT 'real name' `realnam` VARCHAR,
PRIMARY KEY (` id`)
);

Product table ##
the CREATE TABLE test`.`product` `(
` id` the INT (10) the AUTO_INCREMENT the COMMENT the NOT NULL 'commodity ID',
`productname` VARCHAR (30) the COMMENT the NOT NULL 'product name',
` quantity` the INT ( 10) NOT NULL COMMENT 'stocks',
a PRIMARY KEY ( `id`)
);

Sales record table ## from the table
the CREATE TABLE test`.`sale` `(
` id` the INT (10) the NOT NULL the AUTO_INCREMENT the COMMENT "record ID",
`price` DOUBLE (11,2) the COMMENT the NOT NULL 'selling price',
`quantity` INT (10) NOT NULL COMMENT ' number',
` totalprice` DOUBLE (10,2) the COMMENT the NOT NULL 'total',
`saledate` the NOT NULL dATE the COMMENT 'date of sale',
` userid` the INT (10) NOT NULL COMMENT 'salesman id, corresponding to the primary key table users',
`productid` the INT (10) NOT NULL COMMENT 'product id, corresponding to the primary key of the product table',
a pRIMARY kEY (` id`),
CONSTRAINT `fk_uid` a FOREIGN kEY ( `userid`) test`.`users` the REFERENCES` ( `id`),
CONSTRAINT` fk_pid` a FOREIGN KEY ( `productid`) test`.`product` the REFERENCES` ( `id`)
);

Add ## test data, before adding together the main table from the table
INSERT INTO users (username, PASSWORD, realnam) VALUES ( ' boats', '123', 'Diaozhi Fei');
the INSERT the INTO Users (username, PASSWORD, realnam) VALUES ( 'Liu', '223', 'Liu Xin');
the INSERT the INTO Users (username, PASSWORD, realnam) VALUES ( 'large Liu', '323', 'Liu');


INSERT INTO product (productname, quantity) VALUES ( ' Coca Cola', 200 is);
INSERT INTO product (productname, quantity) VALUES ( ' ice tea', 500);
INSERT INTO product (productname, quantity) VALUES ( ' coffee', 10000 );


INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(2,50,100,NOW(),1,1) ;
INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(5,50,250,NOW(),2,2) ;
INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(2,50,100,NOW(),3,1) ;
INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(10,50,500,NOW(),3,3) ;
INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(3,50,150,NOW(),2,1) ;
INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(6,50,300,NOW(),3,2) ;


## 三表连接查询
SELECT s.id,price,s.quantity,totalprice,saledate,userid,productid,u.`realnam`,p.`productname` FROM sale s
LEFT JOIN users u ON u.`id` = s.`userid`
LEFT JOIN product p ON p.`id` = s.`productid`

ORDER BY s.`saledate` DESC

Utils installation package       - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

BaseUtils.java folder

package com.kgc.kh76.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseUtils {
// 定义连接数据库信息
protected static final String DRIVER = "com.mysql.jdbc.Driver";
protected static final String URL = "jdbc:mysql://127.0.0.1/test";
protected static final String USER = "root";
protected static final String PASSWORD = "ok";

// define the database connection object, precompiled sql statement transmission channel, rs result set is
protected Connection Conn = null;
protected the PreparedStatement pstmt = null;
protected the ResultSet RS = null;

// 加载驱动
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

// create a database connection object
public Connection getConn () {
the try {
return the DriverManager.getConnection (the URL, the USER, PASSWORD);
} the catch (SQLException E) {
e.printStackTrace ();
}
return null;
}

// close all database connection object
public void closeAll () {
the try {
IF (RS = null!) {
Rs.Close ();
}
IF (pstmt = null!) {
Pstmt.close ();
}
! IF (Conn = null) {
conn.Close ();
}
} the catch (SQLException E) {
e.printStackTrace ();
}
}

/ **
* Public inquiry method
*
* @param sql transmission sql statement
* @param params precompiled placeholder parameter
* @return rs query result set
* /
public ResultSet executeQuery (String sql, Object ... params) {
// database connection
Conn getConn = ();
the try {
// create a database transmission channel
pstmt = conn.prepareStatement (SQL);
// loop through placeholder parameters
for (int i = 0; i <params.length; i ++ ) {
// set placeholder parameters
pstmt.setObject (I +. 1, the params [I]);
}
// trigger the execution of the query sql statement
RS = pstmt.executeQuery ();
} the catch (SQLException E) {
e.printStackTrace ( );
}
return RS;
}

/ **
* public CRUD operations
* @param sql transmission sql statement
* @Param params precompiled placeholder parameter
* @return rows CRUD operations performed affected
* /
public int the executeUpdate (String SQL, the params Object ...) {
// database connection
Conn getConn = ();
// CRUD operations performed the number of rows affected
int Result = 0;
the try {
// create a database transmission channel
pstmt = conn.prepareStatement (SQL);
// loop through placeholder parameters
for (int i = 0; i <params. length; I ++) {
// set placeholder parameters
pstmt.setObject (I +. 1, the params [I]);
}
// trigger execution of CRUD sql statement
Result = pstmt.executeUpdate ();
} the catch (SQLException E) {
e.printStackTrace ();
} the finally {
// close all database connection object call
closeAll ();
}
return Result;
}
}

Installation package entity       - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 File 1: Users.java

package com.kgc.kh76.entity;

public class Users {
private int id; //INT(10) NOT NULL AUTO_INCREMENT COMMENT '用户id',
private String username; //VARCHAR(20) NOT NULL COMMENT '用户名',
private String password; //VARCHAR(20) NOT NULL COMMENT '密码',
private String realnam; //VARCHAR(20) NOT NULL COMMENT '真实姓名',
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealnam() {
return realnam;
}
public void setRealnam(String realnam) {
this.realnam = realnam;
}

public Users() {
}
public Users(int id, String username, String password, String realnam) {
this.id = id;
this.username = username;
this.password = password;
this.realnam = realnam;
}
@Override
public String toString() {
return "Users [id=" + id + ", username=" + username + ", password=" + password + ", realnam=" + realnam + "]";
}
}

File 2: Sale.java

package com.kgc.kh76.entity;

class Sale {public
Private ID int; // the INT (10) the NOT NULL the AUTO_INCREMENT the COMMENT 'record ID',
Private Double. price; // DOUBLE (11,2) the COMMENT the NOT NULL 'selling price',
Private Quantity int; // the INT (10) NOT NULL COMMENT 'number',
Private Double TotalPrice; // DOUBLE (10,2) the COMMENT the NOT NULL 'total',
Private String SaleDate; // the NOT NULL dATE the COMMENT "date of sale",

private Users user; // INT(10) NOT NULL COMMENT '销售员 id,对应 users 表的主键',
private Product product; // INT(10) NOT NULL COMMENT '商品 id,对应 product 表的主键',
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTotalprice() {
return totalprice;
}
public void setTotalprice(double totalprice) {
this.totalprice = totalprice;
}
public String getSaledate() {
return saledate;
}
public void setSaledate(String saledate) {
this.saledate = saledate;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}

public Sale() {
}
public Sale(int id, double price, int quantity, double totalprice, String saledate, Users user, Product product) {
this.id = id;
this.price = price;
this.quantity = quantity;
this.totalprice = totalprice;
this.saledate = saledate;
this.user = user;
this.product = product;
}
@Override
public String toString() {
return "Sale [id=" + id + ", price=" + price + ", quantity=" + quantity + ", totalprice=" + totalprice
+ ", saledate=" + saledate + ", user=" + user + ", product=" + product + "]";
}
}

File 3: Product.java

package com.kgc.kh76.entity;

public class Product {
private int id; //INT(10) NOT NULL AUTO_INCREMENT COMMENT '商品 id',
private String productname; //VARCHAR(30) NOT NULL COMMENT '商品名称',
private int quantity; //INT(10) NOT NULL COMMENT '库存量',
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

public Product() {
}
public Product(int id, String productname, int quantity) {
super();
this.id = id;
this.productname = productname;
this.quantity = quantity;
}
@Override
public String toString() {
return "Product [id=" + id + ", productname=" + productname + ", quantity=" + quantity + "]";
}
}

During Package Dao      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

What dao yes? ? ?

Folder 1: UsersDao.java    is the interface file. Oriented interface.

 

package com.kgc.kh76.dao;

 

import com.kgc.kh76.entity.Users;

 

interface UsersDao {public
// user name and password query methods
the Users queryUserByUnameAndPwd (String uname, String pwd);
// stressed: general project, is rarely applied delete
}

 

Folder 2: SaleDao.java      is the interface file.

 

package com.kgc.kh76.dao;

import java.util.List;

 

import com.kgc.kh76.entity.Sale;

 

interface SaleDao {public
// add a sales record in the table
// Basic Information: Product Name Quantity Price
int addSale (Sale would like to purchase);

// query for all sales records
// query for paging sales records and sorted according to the date of sale (descending)
List < sale> queryAllSales ();

// The sales record information recorded Change sales ID
int updateSaleById (sale sale);
}

 

Folder 3: ProductDao.java     is the interface file.

 

package com.kgc.kh76.dao;

 

import com.kgc.kh76.entity.Product;

 

interface the ProductDao {public
// list of goods for inventory reduction
// The method of item id of the item updates
int updateProductById (Product Pro);

// number of queries under the trade name of the product inventory
int productQuantity (String proname);
}

 

    Creating impl package Package Penalty for lower DAO    impl file in the Package Penalty for  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

UsersDaoImpl.java

package com.kgc.kh76.dao.impl;

import com.kgc.kh76.dao.UsersDao;

import com.kgc.kh76.entity.Users;
import com.kgc.kh76.utils.BaseUtils;

public class UsersDaoImpl extends BaseUtils implements UsersDao {

@Override
public Users queryUserByUnameAndPwd(String uname, String pwd) {
return null;
}

}

SaleDaoImpl.java

package com.kgc.kh76.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.kgc.kh76.dao.SaleDao;
import com.kgc.kh76.entity.Product;
import com.kgc.kh76.entity.Sale;
import com.kgc.kh76.entity.Users;
import com.kgc.kh76.utils.BaseUtils;

public class SaleDaoImpl extends BaseUtils implements SaleDao {

@Override
public int addSale(Sale s) {
String sql = "INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(?,?,?,NOW(),?,?) ";
int addRes = super.executeUpdate(sql, new Object[] {s.getPrice(),s.getQuantity(),s.getTotalprice(),
s.getUser().getId(),s.getProduct().getId()});
return addRes;
}

@Override
public List <Sale> queryAllSales () {
// create a List <Sale> collection object, a database for storing the acquired result set rs
List <Sale> Sales new new = the ArrayList <Sale> ();
// sql statement defining a query
the StringBuffer new new SB = the StringBuffer ();
sb.append ( "the SELECT s.id,. price, s.quantity, TotalPrice, SaleDate, the userid, ProductID, u.`realnam`, p.`productname`");
sb.append ( "Sale the FROM S");
sb.append ( "the LEFT the JOIN Users U = the ON u.`id` s.`userid`");
sb.append ( "the LEFT the JOIN Product P = s.` the ON p.`id` productid` ");
sb.append (" the ORDER BY s.`saledate` DESC ");

methods // public call query
super.rs = super.executeQuery (sb.toString ());
the try {
// loop through rs The results set
the while (rs.next ()) {
// create a record sales target sale,Data from the loop through the data assigned to the entity class object
Sale sale = new Sale(rs.getInt("s.id"),
rs.getDouble("price"),
rs.getInt("s.quantity"),
rs.getDouble("totalprice"),
rs.getString("saledate"),
new Users(rs.getInt("userid"), null, null, rs.getString("u.realnam")),
new Product(rs.getInt("productid"), rs.getString("p.productname"), 0));
sales.add(sale);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
super.closeAll();
}
return sales;
}

@Override
public int updateSaleById(Sale sale) {
return 0;
}

}

ProductDaoImpl.java

package com.kgc.kh76.dao.impl;

import com.kgc.kh76.dao.ProductDao;
import com.kgc.kh76.entity.Product;
import com.kgc.kh76.utils.BaseUtils;

public class ProductDaoImpl extends BaseUtils implements ProductDao {

@Override
public int updateProductById(Product pro) {
return 0;
}

@Override
public int productQuantity(String proName) {
return 0;
}

}

  Test Package the test inlet main function   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

SaleDaoImplTest.java

package com.kgc.kh76.test;

import java.util.List;

import com.kgc.kh76.dao.SaleDao;
import com.kgc.kh76.dao.impl.SaleDaoImpl;
import com.kgc.kh76.entity.Product;
import com.kgc.kh76.entity.Sale;
import com.kgc.kh76.entity.Users;

public class SaleDaoImplTest {

public static void main(String[] args) {
SaleDao dao = new SaleDaoImpl();
//新增
//创建Sale对象
Users user = new Users();
user.setId(3);
Product product = new Product();
product.setId(3);
Sale sale = new Sale(0, 11, 100, 1100, null, user, product);
int addRes = dao.addSale(sale);
System.out.println("addRes:"+addRes);

List<Sale> sales = dao.queryAllSales();
System.out.println("ID\t商品\t单价\t数量\t总价\t销售日期\t\t销售员\t");
for (Sale s : sales) {
System.out.println(s.getId()+"\t"+s.getProduct().getProductname()+
"\t"+s.getPrice()+"\t"+s.getQuantity()+"\t"+s.getTotalprice()+
"\t"+s.getSaledate()+"\t"+s.getUser().getRealnam());
}
}

}

     - - - - - -- - -- -- - - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -

     - - - - - -- - -- -- - - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -

     - - - - - -- - -- -- - - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -

     - - - - - -- - -- -- - - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -

 

 


 

 


day20191009 Wednesday and teachers and teacher trainers communicate notes
1. For questions himself, the right medicine. Have a choice, you can not learn anything.
2. four hanging branches, university graduate can do? Then you can be admitted Nanlin, is lazy, intelligence is no problem.
3. a lot of effort, the world's injustices and more. Find their own balance.
4.4 My own training and learning problems: 1) the car on the way back and forth to see the endorsement on the subway, other times a day to see the code of the code of the teacher to understand the most basic knowledge, write, know step 2) and then set the goal of their own, not look 1 hour and then write out the walking dead can not understand today. Day thing day complete. Look at a lot of their work. 3) shots, shots. Record screen. 4) it would not be something must be done. Intelligence is no problem, do a good job. . To work and to learn. Upstream. Good moment.
5.5. Tell the truth, do not must bear responsibility. 1) willing to learn to spend their own time, time is the sponge in the water, coffee time. 2) ask people to solve the problem, ask the great God, ask the teacher, to solve problems, teaching every student can learn new knowledge and adapt to the environment, life is limited, do the moment this time, graduation design. I asked again ignore, ask someone else to manage up, ask questions and solve problems.
Theory is a theory. Practice makes perfect. Yes listen, do not listen to anything. filter.
you're right! But their point of view.

6. revised down to work out of, timely correction, error correction in a timely manner. Dictation.

7. You have to prove their ability, know as soon as possible as soon as possible after the job on the well, perfect, go all out, whatever.

8. spend too little time and effort, copying three times.

9. different time periods need to change their status and way, there is a better way of learning. I will ask to date, say, solve the problem.
Ask people, ask powerful people, people all around.

10. Write 6 times, will be able to understand.

11. With time, strokes fell great oaks. Spend the effort is not enough.

To study diligently and seriously concentrate, adjustment of status, activity, and more practice, patiently, ask, check. Solve the problem.

Adults, their lives take in their own hands, their actions determine his life.
Observe, ask, know and solve problems.
You did not have to pay to complete the job responsibilities. After the first read write
other people say is people say, I was on my own, own their own responsibility.
Thick skin. To wear the crown, must bear its weight. I want to get must be paid. equivalent. Equivalent exchange. Each life are not easy.
A good memory as bad written.
Notes offline, online to see video. Reviewing the Old.
Writing typing dignified posture will not be tired. Self-discipline to be free.
Avoid impetuous. Precipitation, think about the worst thing.
Heart started.
Only one girl, and got to know the great God. And good about yourself.
Men are created equal.
Priorities can not grasp everything, you have a choice. There direction of
the first is the day talking about the course, the most important.
Talk nonsense. Do practical things.
And their ratio, vary, but should reflect, efficiency, and why others can do their own can not do it?
You can not ask, you can ask the online. Coursework. Ask people, ask good people.
I do not shameful, not asked to solve the problem.
Understand. do you understand? understand? You carefully read several times? You seriously done several times? 6 times have you?

 

Guess you like

Origin www.cnblogs.com/effortandluck/p/11646908.html