Java JDBC
发布日期:2022-02-14 16:09:31
浏览次数:24
分类:技术文章
本文共 8052 字,大约阅读时间需要 26 分钟。
JDBC 基础学习总结
- java数据库包 java.sql.*
- JDBC主要过程
- 加载驱动:Class.forName(“com.mysql.jdbc.Driver”);
- 获得数据库连接:DriverManager常用其getConnection(String url,String username,String password)方法进行数据库连接;
- 创建Statement 或PreparedStatement:用于向数据库发送需要执行的sql语句获得结果集;
- 执行sql语句:得到ResultSet结果集;
- 解析返回结果集 ;
- 关闭连接;
Statement接口(多用于不带参执行sql语句)
- 得到Statement实例:Connection的createStatement();
- 常用方法;
- boolean excute(String sql):执行给定sql语句,用于不返回结果;
- ResultSet excuteQuery(String sql):执行给定sql语句,用于返回结果;
- int excuteUpdate(String sql):执行给定 SQL 语句,该语句可能为 INSERT、UPDATE 或 DELETE 语句成功的条数
PreparedStatement接口继承自Statement(多用于带参数查询,其有自动校验格式问题)
- 得到PreparedStatement实例:Connection的prepareSatement(String sql)方法;
- 常用方法:
- setString(int parameterIndex, String x):将指定参数设定为指定字符串;
- setTimestamp(int parameterIndex, Timestamp x):该方法中常用到生成Timestamp:new java.sql.Timestamp(Date.getTime());
- boolean excute():常用来执行setxxx语句;
- ResultSet executeQuery():用来得到结果集;
- setObject(int parameterIndex, Object x):自动将给定参数将被转换为相应 SQL 类型
ResultSet接口
- 常用方法:
- next():将光标从当前位置向前移一行;用来解析时判断是否还有数据;
- getxxx():常用来给对应Dao中对应类属性赋值;
PreparedStatement的增、删、改
-
通常将数据库的url、user(用户名)、password设为常量;
private static final String CONN_URL = "jdbc:mysql://localhost:3306/需连接数据库名?useUnicode=true&characterEncoding=utf8";private static final String USER = "root";private static final String PASSWORD = "root";public static void insert(String username, String password, Date regDate) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(CONN_URL, USER, PASSWORD); String sql = "insert into user(username,passwd,reg_time)values(?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); ps.setTimestamp(3, new java.sql.Timestamp(regDate.getTime())); ps.execute(); System.out.println("执行成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } }} public static void delete(String username) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(CONN_URL, USER, PASSWORD); String sql = "delete from user where username=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.execute(); System.out.println("执行成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }public static void update(int id,String password) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(CONN_URL, USER, PASSWORD); String sql = "update user set passwd=? where user_id=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, password); ps.setInt(2, id); int count = ps.executeUpdate(); System.out.println("执行成功,共影响了"+count+"条"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
JDBCHelper
public class DBHelper { private Connection connection; private ListcloseableList= new ArrayList<>(); /** * 得到链接 * * @return * @throws SQLException * @throws FileNotFoundException */ public Connection getConn() throws SQLException{ try { if (connection==null) { /*Class.forName("com.mysql.jdbc.Driver"); //properties文本的到相应url、user、password Properties prop = new Properties(); String path = this.getClass().getClassLoader().getResource("mysql.properties").getPath(); FileInputStream fis = new FileInputStream(path); prop.load(fis); String url = prop.getProperty("conn_url"); String user = prop.getProperty("user"); String password = prop.getProperty("password");*/ Properties prop = new Properties(); System.out.println( this.getClass().getClassLoader().getResource("")); System.out.println( this.getClass().getClassLoader().getResource("config/sxevn.properties").getPath()); InputStream fis = this.getClass().getResourceAsStream("/config/sxevn.properties"); prop.load(fis); Class.forName(prop.getProperty("jdbc.driverClassName")); String url = prop.getProperty("jdbc.url"); String user = prop.getProperty("jdbc.username"); String password = prop.getProperty("jdbc.password"); connection = DriverManager.getConnection(url, user, password); closeableList.add(connection); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return connection; } /** * 开启事务 * @throws SQLException */ public void startTransaction() throws SQLException{ getConn(); connection.setAutoCommit(false); } /** * 回滚 * @throws SQLException */ public void rollback() throws SQLException{ connection.rollback(); connection.setAutoCommit(true); } /** * 提交 * @throws SQLException */ public void commit() throws SQLException{ connection.commit(); connection.setAutoCommit(true); } /** * 执行查询 * * @param sql * 预编译的sql,带?占位 * @param params * sql中需要代入的参数 * @return * @throws SQLException */ public ResultSet executeQuery(String sql, Object[] params) throws SQLException{ getConn(); ResultSet rs = null; PreparedStatement ps=null; ps = connection.prepareStatement(sql); closeableList.add(ps); for (int i = 1; i <= params.length; i++) { ps.setObject(i, params[i - 1]); } rs = ps.executeQuery(); closeableList.add(rs); return rs; } /*public ResultSet executeQuery(String sql) throws SQLException{ getConn(); ResultSet resultSet = null; Statement statement = connection.createStatement(); resultSet = statement.executeQuery(sql); return resultSet; }*/ public ResultSet executeQuery(String sql) throws SQLException{ ResultSet rs = null; PreparedStatement ps=null; getConn(); try { ps = connection.prepareStatement(sql); closeableList.add(ps); rs = ps.executeQuery(); closeableList.add(rs); } catch (SQLException e) { e.printStackTrace(); } return rs; } /** * 执行insert * @param sql * @param params * @return * @throws SQLException */ public boolean execute(String sql, Object[] params) throws SQLException{ boolean rs = false; PreparedStatement ps=null; getConn(); ps = connection.prepareStatement(sql); closeableList.add(ps); for (int i = 1; i <= params.length; i++) { ps.setObject(i, params[i - 1]); } ps.execute(); rs=true; return rs; } /** * 执行更新(插入) * @param sql * @param params * @return * @throws SQLException */ public int executeUpdate(String sql,Object[] params) throws SQLException{ getConn(); PreparedStatement ps= connection.prepareStatement(sql); closeableList.add(ps); for (int i = 1; i <= params.length; i++) { ps.setObject(i, params[i - 1]); } return ps.executeUpdate(); } /** * 清理资源 */ public void cleanup() { try { connection.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } //将资源倒序 Collections.reverse(closeableList); //挨个清理 for(AutoCloseable ac : closeableList){ //System.out.println(ac); if(ac!=null){ try { ac.close(); } catch (Exception e) { e.printStackTrace(); } } } closeableList.clear(); }}
#conn_url=jdbc:mysql://localhost:1433/sx_test?useUnicode=true&characterEncoding=utf8#user=zhangs#password=123456jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:1433/sx_test?useUnicode=true&characterEncoding=utf8jdbc.username=zhangsjdbc.password=123456
转载地址:https://blog.csdn.net/qq_29593573/article/details/76034747 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年04月27日 06时35分41秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
关于RS-485总线,这篇很详细
2019-04-29
关于2021年电赛的一些想法,看到就是赚到!
2019-04-29
教你一秒分辨真假芯片!
2019-04-29
抽奖 | 送STM32开发板
2019-04-29
光立方,永远的神!
2019-04-29
学习STM32很简单?
2019-04-29
电赛 | 电源题软件如何准备?
2019-04-29
手把手教你DIY一款属于自己的万能红外遥控器!
2019-04-29
速看 | 电子元器件如何确定好坏?
2019-04-29
485通信自动收发电路,历史上最详细的解释
2019-04-29
【视觉盛宴三】不好意思,这些线材接口的横截面真的没见过
2019-04-29
一位头发发白的神人教你怎么写程序,运维,买电脑,写文章,平面设计!
2019-04-29
【第二期】那些设计漂亮、有创意的电路板!
2019-04-29
【第三期】那些设计漂亮、有创意的电路板!
2019-04-29
继续推荐公众号~
2019-04-29
「第二篇」全国一等奖,经验帖。
2019-04-29
「第三篇」全国电子设计竞赛,这些你必须知道的比赛细节,文末附上近十年电赛题目下载...
2019-04-29
5G小科普(漫画版,So easy!)
2019-04-29
无人再提华强北
2019-04-29
千万不要小瞧那些不好好写代码的程序员
2019-04-29