Home >Java >Javagetting Started >What is the encapsulation process of jdbc in java

What is the encapsulation process of jdbc in java

王林
王林Original
2019-11-25 14:13:392335browse

What is the encapsulation process of jdbc in java

This article introduces the jdbc encapsulation process from the java introduction column. I hope it can help students who are learning java!

JDBC encapsulation process:

Declare jdbc parameters

Declare jdbc variables

Load driver

Create connection object

Create SQL command

Create SQL command object

Placeholder assignment

Execute SQL command

Process the result

Close the resource

The encapsulation example is as follows:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.bjsxt.entity.DBUtil;
public class TestTrainsaltion {
	public static void main(String[] args) {
		//事物的练习
		/**
		 * 1、创建jdbc参数
		 * 2、创建jdbc变量
		 * 3、加载驱动
		 * 4、创建连接
		 * 5、创建SQL命令对象
		 * 6、创建SQL命令
		 * 7、执行SQL命令
		 * 8、处理结果
		 * 9、关闭资源
		 */
//		//1、创建jdbc参数
//		String driver = "oracle.jdbc.OracleDriver";
//		String url="jdbc:oracle:thin:@localhost:1521:XE";
//		String username="scott";
//		String passwd="123456";
//		//创建jdbc变量
		Connection conn = null;
		PreparedStatement ps = null;
		//3、加载驱动
		try {
//			Class.forName(driver);
//			//4、创建连接
//			conn = conn = DriverManager.getConnection(url, username, passwd);
			conn=DBUtil.getConnection();
			//5、开启事物
			conn.setAutoCommit(false);		
			//6、创建SQL命令对象
			String sql="update t_account set money=money+? where aname=?";
			//7、创建命令对象
			ps = conn.prepareStatement(sql);
			//8、给占位符赋值
			int i=0;
			//转账
			ps.setDouble(1, 500);
			ps.setString(2, "李四");
			int executeUpdate4 = ps.executeUpdate();
			int executeUpdate3 = executeUpdate4;
			int executeUpdate2 = executeUpdate3;
			int executeUpdate = executeUpdate2;
			i = executeUpdate;
			ps.setDouble(1, -500);
			ps.setString(2, "张三");
			i+=ps.executeUpdate();
			//处理结果
			if(i>=2){
				System.out.println("转账成功");
			}else{
				System.out.println("转账失败");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

The above is the detailed content of What is the encapsulation process of jdbc in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn