jdbc Advanced - Advanced tools

My website: Welcome Welcome

Advanced JDBC

PreparedStatement

Prepared statements, this interface inherits Statement Interface

1. solve the problem of string concatenation

2. To solve the problem sql injection

3. Let a little higher efficiency

Implementation steps

The foregoing steps are the same database connection

When you use SQL statements to get an object

将Statement st = conn.createStatement();

Replace PreparedStatement st = conn.prepareStatement (sql); // precompiled sql
need not pass sql during execution;

String sql = "select * from login where username=? and password=?";
			PreparedStatement pStatement = conn.prepareStatement(sql);
			pStatement.setString(1, username);
			pStatement.setString(2, pwd);
			ResultSet set = pStatement.executeQuery();

Demo

There are two ways to determine Login

package com.ifueen.homework.dao.impl;

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

import com.ifueen.classtest.util.JDBCUtil;
import com.ifueen.classtest.util.JDBCUtilDataSource;
import com.ifueen.homework.dao.LoginDao;
import com.sun.javafx.binding.Logging;

public class LoginDaoImpl implements LoginDao{

	/**
	 * 第一种判断登录的方式
	 */
	@Override
	public void login(String username, String pwd) {
		// TODO Auto-generated method stub
		Connection conn = JDBCUtilDataSource.getinstance().getconn();
		try {
			Statement statement = conn.createStatement();
			String sql = "select * from login";
			ResultSet rs = statement.executeQuery(sql);
			if (rs.next()) {
				if (!rs.getString("username").equals(username)) {
					System.out.println("你有这个账户吗?嗯?弟弟");
				}else{
					if (rs.getString("username").equals(username) && rs.getString("password").equals(pwd)) {
						System.out.println("登录成功");
					}else{
						System.out.println("密码都记不住吗弟弟?");
					}
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

    /**
	 * 第二种
	 * 使用prepareStatement来进行加载,避免了sql注入问题
	 */
	@Override
	public void login2(String username, String pwd) {
		// TODO Auto-generated method stub
		Connection conn = JDBCUtilDataSource.getinstance().getconn();
		try {
			String sql = "select * from login where username=? and password=?";
			PreparedStatement pStatement = conn.prepareStatement(sql);
			pStatement.setString(1, username);
			pStatement.setString(2, pwd);
			ResultSet set = pStatement.executeQuery();
			if (set.next()) {
				if (set.getString("username").equals(username) && set.getString("password").equals(pwd)) 
					System.out.println("登录成功");
			}else{
				System.out.println("密码都记不住吗弟弟?");
			}
			
			JDBCUtil.getinstance().getclose(pStatement, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

? Transaction

What is a transaction

Services: program inside a set of operations, or succeed, or fail;

Transaction Example:
Bank Transfer Function: bank / money
Xiao Feng and red:
Xiao Feng: 10000 yuan red: 0 dollars

Transfer: Xiao Feng turn red to give 1000 dollars
Analysis: transfer money required to provide two sql, but programmers make mistakes, comparison code was wrong.

If an error occurs when charge, so Xiao Feng's net balance of the red, but did not receive, so unreasonable

This time you need to use the transaction operations

Operation of its services: to define the beginning of a transaction, and then the data modification operations, then if you submit (commit), these changes will be preserved permanently, if the rollback (rollback), database management system will discard all your changes the state back to the start time of the transaction.

Four characteristics of things (interview questions)

Four characteristics of things: ACID

Atomicity: a set of operations indivisible

Consistency: before and after the operation has been required

Isolation: Concurrent programming, operations between multiple threads does not meet the impact

Persistence: The persistence data in memory to disk

Demo

Using the transfer function of the transaction implementation

package com.ifueen.homework.dao.impl;

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

import com.ifueen.classtest.util.JDBCUtilDataSource;
import com.ifueen.homework.dao.Transfer;
import com.sun.org.apache.bcel.internal.generic.Select;

public class TransferDaoImpl implements Transfer{

	/**
	 * 查询账户余额
	 */
	@Override
	public double select(String name) {
		Double b = null;
		// TODO Auto-generated method stub
		Connection conn = JDBCUtilDataSource.getinstance().getconn();
		String sql = "select balance from transfer where name = ?";
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				b = rs.getDouble("balance");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return b;
	}
	
	
	/**
	 * 转账功能
	 */
	@Override
	public void transfer(String name, String name2, double money) {
		// TODO Auto-generated method stub
		Connection conn = JDBCUtilDataSource.getinstance().getconn();
		try {
			//设置事务的自动提交为false,即不自动提交
			conn.setAutoCommit(false);
			String sql = "update transfer set balance= ? where name = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setDouble(1, select(name)-money);
			ps.setString(2, name);
			ps.executeUpdate();
			//测试意外情况
			//System.out.println(1/0);
			//另一个账户增加
			String sql1 = "update transfer set balance= ? where name = ?";
			PreparedStatement ps1 = conn.prepareStatement(sql1);
			ps1.setDouble(1, select(name2)+money);
			ps1.setString(2, name2);
			ps1.executeUpdate();
			
			//完成操作提交事务
			conn.commit();
			JDBCUtilDataSource.getinstance().getclose(ps,conn);
			JDBCUtilDataSource.getinstance().getclose(ps1,conn);
			System.out.println("转账成功啦");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				//设置事务的自动回滚
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
}

note! In MySQL, InnoDB supports foreign key. Transactional, MyISAM does not support foreign keys, does not support transactions

To get the primary key using JDBC

Why do I need to get the Id?

Now we insert a piece of data, but do not know the id of the data is how much, and we sometimes, you need this id.

For example, we insert the product table a piece of data, its number is 200, but the product list which did not represent the number of fields, and product_store table which contains storeNum, all of us should be inserted after the data, while the need to insert a data into product_store table inside ; - this time we need to get the product table newly inserted id;

A method to get the primary key:

Connection conn = JDBCUtilDataSource.getinstance().getconn();
			String sql = "insert into student (name,age) value (?,?)";
			PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, name);
			ps.setInt(2, age);
			ps.execute();
			//拿到主键的集合
			ResultSet rs = ps.getGeneratedKeys();
			while (rs.next()) {
				System.out.println(rs.getLong(1));
			}

connection pool

Why should the connection pool?

Every request to create a connection, and therefore a waste of resources (memory), while when 1,000 people visited, it will take up a lot of resources, so it is a waste of time and vessel operating system crashes

Understanding the connection pool

Conserve memory resources to maintain the connection object life cycle
very beginning to create some connection objects into the connection pool can get a connection request to operate directly in the database connection pool

After the operation is complete release the connection back to the connection pool waiting for the next requested to use
when the initial connection created some minimum number of concurrent connection requests when created more connections maximum connection

Common connection pool

dbcp (spring Integration)

c3p0

druid (common)

Use dbcp connection pool

Note: Before using the connection pool requires importing the package

Properties prop =new Properties();
    prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"))
    DataSource ds = BasicDataSourceFactory.createDataSource(prop);
    Connection conn=ds.getConnection();
Published 87 original articles · won praise 7 · views 20000 +

Guess you like

Origin blog.csdn.net/f2315895270/article/details/99643814