将Java连接数据库操作封装到MySQL类中
public class MySQL { final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; final String DB_URL = "jdbc:mysql://localhost:3306/student_message?serverTimezone=UTC&characterEncoding=utf-8"; final String USER = "root"; final String PASS = "1234"; Connection conn = null; Statement stmt = null; public void account_lo(int account,int password)//账户注册,参数为两个整形 { try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 System.out.println(" 实例化Statement对象..."); stmt = conn.createStatement(); String sql; sql = "insert into account values("+account+","+password+")";//向数据库中插入数据 stmt.execute(sql); System.out.println("save successful"); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } System.out.println("Goodbye!"); } }
该类主要实现了账户注册的方法,即增的方法。
实现删,改,查也是类似方法。
本文作者:又一岁荣枯
本文链接:https://www.cnblogs.com/java-six/p/15511222.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步