使用jdbc连接数据库插入数据
使用jdbc连接数据库操作数据库进行增删改查
package com.iflytek.jtcn.service.impl; import com.iflytek.jtcn.model.po.PassFlowStatisticsBean; import org.junit.jupiter.api.Test; import java.sql.*; import java.util.*; import java.util.Date; public class JDBC { /*private String userName = " "; private String passwordName = " "; //private String urlName = "jdbc:oracle:thin:@34.115.123.11:1521/tspw"; private String urlName = "jdbc:oracle:thin:@34.115.125.11:1521:JTDN";*/ private Connection conn = null;//连接对象 private ResultSet rs = null;//结果集对象 private Statement sm = null; //用于连接数据库(oracle 其他数据库改一下驱动即可) public static Connection getOracleConn() { Connection conn = null; try { Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序 String url = "jdbc:oracle:thin:@34.115.126.11:1521/tlspw"; String username = ""; String password = ""; conn = DriverManager.getConnection(url, username, password);// 获取连接 } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 插入单条数据 * * @param conn * @param sql * @return */ public static boolean insert(Connection conn, String sql) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); return ps.executeUpdate() > 0 ? true : false; } catch (SQLException e) { e.printStackTrace(); } finally { try { if (ps != null) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } return false; } @Test public static void insertData(PassFlowStatisticsBean bean){ String id = UUID.randomUUID().toString(); String sql = "insert into FLOW_STATISTICS_DATA(ID,CROSS_ID,TASK_ID,CREATE_TIME,TIMESTAMP,EW,ES,EN,WE,WS,WN,SN,SE,SW,NS,NE,NW) " + "values('" + id + "','"+bean.getCrossId()+"','"+bean.getTaskId()+"','"+bean.getCreateTime()+"', '"+bean.getTimestamp()+"', '"+bean.getEw()+"', '"+bean.getEs()+"', '"+bean.getEn()+"', '"+bean.getWe()+"', '"+bean.getWs()+"', '"+bean.getWn()+"', '"+bean.getSn()+"', '"+bean.getSe()+"', '"+bean.getSw()+"', '"+bean.getNs()+"', '"+bean.getNe()+"', '"+bean.getNw()+"')"; System.out.println(sql); Connection oracleConn = getOracleConn(); insert(oracleConn, sql); try { oracleConn.commit(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { String id = UUID.randomUUID().toString(); String sql = "insert into FLOW_STATISTICS_TEST(ID,CROSS_ID,TIMESTAMP,EW,ES,EN,WE,WS,WN,SN,SE,SW,NS,NE,NW) " + "values('" + id + "','te1st', '男', '男', '男', '男', '男', '男', '男', '男', '男', '男', '男', '男', '男')"; System.out.println(sql); Connection oracleConn = getOracleConn(); insert(oracleConn, sql); try { oracleConn.commit(); } catch (SQLException e) { e.printStackTrace(); } } }
原创不易,如果感觉不错,希望给个推荐!您的支持是我写作的最大动力!