连接mysql数据库的javabean,修改url数据库连接字符串和驱动程序加载代码,即可成为通用的数据库连接BEAN。
package com.common; import java.sql.*; public class DataBaseConn { public Connection conn = null; public void createConn(){ String url = "jdbc:mysql://localhost:3306/employeeDb"; String username = "root";// 数据库用户名 String password = "root";// 数据库密码 if(conn == null){ try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,username,password); }catch(Exception e){e.toString();} } } public Connection getConn(){ if(conn == null){ createConn();} return conn; } public void closeConn(){ if(conn != null){ try { conn.close(); conn = null; } catch (Exception e) { e.printStackTrace(); } } } public ResultSet executeQuery(String sql) { ResultSet rs = null; if (conn == null) {createConn();} try { Statement stmt = conn.createStatement(); rs = stmt.executeQuery(sql); } catch (Exception e) { e.printStackTrace(); } return rs; } public void executeUpdate(String sql) { if (conn == null) {createConn(); } try { Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } } }
再操作数据库,通过usebean动作标记调用该javabean即可,希望对你有所帮助。
125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/9002.html