mysql学习笔记3

xiaoxiao2021-02-28  6

JDBC的API的详解: DriverManager: * 注册驱动: * 获得连接: Connection: * 获得执行SQL语句对象. * Statement createStatement(); * PreparedStatement prepareStatement(String sql); * CallableStatement prepareCall(String sql); * 进行事务管理: * setAutoCommit(boolean flag); * commit(); * rollback(); Statement: * 执行SQL语句: * int executeUpate(String sql); –执行insert update delete语句. * ResultSet executeQuery(String sql); –执行select语句. * boolean execute(String sql); –执行select返回true 执行其他的语句返回false.

ResultSet: * 遍历结果集:next(); * 获得结果集中的数据.getXXX(int c); getXXX(String name); 抽取工具类: package com.itheima.jdbc.utils;

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties;

/** * JDBC的工具类 * @author apple * */ public class JDBCUtils { public static final String DRIVERCLASS; public static final String URL; public static final String USERNAME; public static final String PASSWORD;

static{ // 获得属性文件中的数据. Properties properties = new Properties(); try { properties.load(new FileInputStream("src/db.properties")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } DRIVERCLASS = properties.getProperty("jdbc.driverClass"); URL = properties.getProperty("jdbc.url"); USERNAME = properties.getProperty("jdbc.username"); PASSWORD = properties.getProperty("jdbc.password"); } // 加载驱动: public static void loadDriver(){ try { Class.forName(DRIVERCLASS); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 获得连接: public static Connection getConnection(){ loadDriver(); Connection conn = null; try { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } // 释放资源: public static void release(Statement stmt,Connection conn){ if(stmt != null){ try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } stmt = null; } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } public static void release(ResultSet rs,Statement stmt,Connection conn){ if(rs!= null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } if(stmt != null){ try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } stmt = null; } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } }

}

分类的CRUD的操作详见JDBCDemo1.java 记得下载,mysql对应的数据库驱动包。

转载请注明原文地址: https://www.6miu.com/read-1750305.html

最新回复(0)