原创 OA圈子
在开发中,我们有时候会涉及到链接第三方数据库视图或者中间库,此时我们需要在OA代码中去创建相应的链接工具类,下面我们分享链接工具类的方法:
链接工具类:
import com.seeyon.ctp.common.AppContext;
import java.sql.*;public class JdbcUtil {private static final String className = AppContext.getSystemProperty("ykk.driverClassName"); //驱动private static final String url = AppContext.getSystemProperty("ykk.dburl"); //链接串private static final String userName = AppContext.getSystemProperty("ykk.dbuserName"); //用户名private static final String password = AppContext.getSystemProperty("ykk.dbpassword"); //密码//连接数据库public static Connection getCon() {Connection con = null;try {Class.forName(className);con = (Connection)DriverManager.getConnection(url, userName, password);} catch (Exception e) {e.printStackTrace();}return con;}//关闭数据public static void closeDB(ResultSet rs,PreparedStatement pstmt,Connection con) {try {if (rs != null) {rs.close();}if (pstmt != null) {pstmt.close();}if (con != null) {con.close();}} catch (Exception e) {e.printStackTrace();}}
}
实现的增删改查方法:
查询方法:
public static List<JSONObject> query(String rq) {Connection con = null;PreparedStatement pstmt = null;ResultSet rs = null;JSONObject m = null;List<JSONObject> list = new ArrayList<JSONObject>();try {con = JdbcUtil.getCon();String sql = "select field0001,field0002 from talbe where field0003 >= ?"; pstmt = (PreparedStatement)con.prepareStatement(sql);pstmt.setString(1, rq);rs = (ResultSet)pstmt.executeQuery();while (rs.next()) {m= new JSONObject();m.accumulate("qxName",rs.getString("field0001"));m.accumulate("qxAdmin",(rs.getString("field0002")==null?"":rs.getString("field0002")));.....list.add(m);}} catch (Exception e) {e.printStackTrace();} finally {JdbcUtil.closeDB(rs, pstmt, con);}return list;}
修改
public static void update(String table,String qx,String col,String qxval,String colval) {Connection con = null;PreparedStatement pstmt = null;ResultSet rs = null;try {con = JdbcUtil.getCon();String sql = "update table set col=? where qx=?";pstmt = (PreparedStatement)con.prepareStatement(sql);pstmt.setString(1, colval);pstmt.setString(2, qxval);pstmt.executeUpdate();} catch (Exception e) {e.printStackTrace();} finally {ConnDB.closeDB(rs, pstmt, con);}}
下面分享几个场景的数据库连接驱动和链接串
oracle:
链接驱动:oracle.jdbc.driver.OracleDriver
链接串:jdbc:oracle:thin:@127.0.0.1:1521:v3x
对应的jar包:ojdbc14.jar
sqlserver:
链接驱动:net.sourceforge.jtds.jdbc.Driver
链接串:jdbc:jtds:sqlserver://127.0.0.1:1433/DBName
对应的jar包:sqljdbc4.jar
mysql:
链接驱动:com.mysql.jdbc.Driver
链接串:jdbc:mysql://127.0.01:3306/a8?characterEncoding=UTF-8
对应的jar包:mysql-connector-j-8.0.33.jar
达梦:
链接驱动:dm.jdbc.driver.DmDriver
链接串:jdbc:dm://127.0.0.1:5236
对应的jar包:DmJdbcDriver16-8.1.3.140.jar
人大金仓:
链接驱动:com.kingbase8.Driver
链接串:jdbc:kingbase://localhost:54321/myDatabase
对应的jar包:kingbase8-8.6.0.jar
jar包下载地址
https://mvnrepository.com/,可以通过该网站进行搜索下载,如下:
写在最后:以上代码可以直接复制使用,只需要替换相应的jar包,链接驱动和链接串就可以了。