我有个List集合(泛型集合),我想使用java代码通过insert语句,把这个List集合中的数据添加到oracle数据库中!应该怎么做?打个比方我有个User的实体类(里面有还有个id,用户名,密码),我的List<User> list=new ArrayList<User>(); User u1=new User(1,'zhangsan','zhangsan'); User u2=new User(2,'lisi','lisi');list.add(); list.add(u1); list.add(u2); public static boolean runInsert(){},我在这个runInsert中怎样写代码可以把这个List集合添加到数据库中。不使用存储过程!
3 回答
达令说
TA贡献1821条经验 获得超6个赞
如下
Class.forName( "oracle.jdbc.driver.OracleDriver" ); String url = "jdbc:oracle:thin:@你的主机ip :1521:orcl" ; // 设置连接字符串 String username = "你的用户名" ; String password = "你的密码" ; Connection con=java.sql.DriverManager.getConnection(url,user,password); Statement stmt = con.createStatement(); StringBuffer sql = new StringBuffer( "insert into user values (" + list.get( 1 ).getId()+ ", " +list.get( 1 ).getUserName()+ ", " +list.get( 1 ).getPassword()+ ")" ); for ( int i = 2 ; i < list.size(); i++){ sql.append( ", (" + list.get(i).getId()+ ", " +list.get(i).getUserName()+ ", " +list.get(i).getPassword()+ ")" ); // } sql.append( ";" ); ResultSet rs = stmt.executeQuery(sql); rs.close(); stmt.close(); con.close(); |
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
Class.forName( "com.mysql.jdbc.Driver" ); Connection conn = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/kxh?useServerPrepStmts=false&rewriteBatchedStatements=true" , "root" , "root" ); conn.setAutoCommit( false ); PreparedStatement ps = conn.prepareStatement( "insert into user_table(id,userName,passWord) values(?,?,?)" ); List<User> list= new ArrayList<User>(); //你的list for (User user:list) { ps.setInt( 1 , user.getId()); ps.setString( 2 , user.getUsername()); ps.setString( 3 , user.getPassword()); ps.addBatch(); //加入批量 } ps.executeBatch(); //执行批量 conn.commit(); //提交事务 ps.close(); conn.close(); |
添加回答
举报
0/150
提交
取消