zoukankan      html  css  js  c++  java
  • server用JDBC对mysql数据库进行操作


    1:获取数据库连接

    Connection connection=getConnection();

    2:准备SQL语句

    3:调用Connection的creatStatement()方法获取Statement对象运行SQL语句

    (注:Statement对象处理的SQL语句仅仅能是INSERT,UPDATE或DELETE)
    statement=connection.createStatement();
    statement.execute(SQL);

    4:关闭Statement对象

    5:关闭数据库连接


    将数据库连接等操作进行封装:

    附:JDBCTools.java
    /**
     * JDBC 的工具类
     * 
     * 当中包括: 获取数据库连接, 关闭数据库资源等方法.
     */
    public class JDBCTools {
    	
    	//处理数据库事务的
    	//提交事务
    	public static void commit(Connection connection){
    		if(connection != null){
    			try {
    				connection.commit();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	
    	//回滚事务
    	public static void rollback(Connection connection){
    		if(connection != null){
    			try {
    				connection.rollback();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	
    	//開始事务
    	public static void beginTx(Connection connection){
    		if(connection != null){
    			try {
    				connection.setAutoCommit(false);
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	
    	private static DataSource dataSource = null;
    
    	//数据库连接池应仅仅被初始化一次. 
    	static{
    		dataSource = new ComboPooledDataSource("helloc3p0");
    	}
    	
    	public static Connection getConnection() throws Exception {
    		return dataSource.getConnection();
    	}
    
    	public static void releaseDB(ResultSet resultSet, Statement statement,
    			Connection connection) {
    
    		if (resultSet != null) {
    			try {
    				resultSet.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    
    		if (statement != null) {
    			try {
    				statement.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    
    		if (connection != null) {
    			try {
    				//数据库连接池的 Connection 对象进行 close 时
    				//并非真的进行关闭, 而是把该数据库连接会归还到数据库连接池中. 
    				connection.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    
    }
    


    附:MySqlTools.java,对数据库进行操作
    	public static void update(String SQL){
    		Connection connection = null;
    		Statement statement=null;
    		try {
    			connection = JDBCTools.getConnection();
    			statement=connection.createStatement();
    			statement.execute(SQL);
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			JDBCTools.releaseDB(null, null, connection);
    		}
    	}



  • 相关阅读:
    三、Antd react 组件调用ref的用法获取实例
    三、gitextension 报错无法检出版本库的时候
    二、安装引入 antd
    一、React项目骨架搭建
    一、JAVA基础知识
    五、Maven创建Spring(IDEA2019-3-3)
    python爬取快手ios端首页热门视频
    接口测试之基础篇--http协议
    一些测试面试题
    性能测试一些相关的概念
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/7047232.html
Copyright © 2011-2022 走看看