请问我该如何使用java代码向oracle数据库一次性插入多条数据?

我有个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集合添加到数据库中。不使用存储过程!


catspeake
浏览 286回答 3
3回答

达令说

如下Class.forName("oracle.jdbc.driver.OracleDriver");String&nbsp;url&nbsp;=&nbsp;"jdbc:oracle:thin:@你的主机ip&nbsp;:1521:orcl";//&nbsp;设置连接字符串String&nbsp;username&nbsp;=&nbsp;"你的用户名";String&nbsp;password&nbsp;=&nbsp;"你的密码";Connection&nbsp;con=java.sql.DriverManager.getConnection(url,user,password);Statement&nbsp;stmt&nbsp;=&nbsp;con.createStatement();&nbsp;StringBuffer&nbsp;sql&nbsp;=&nbsp;new&nbsp;StringBuffer("insert&nbsp;into&nbsp;user&nbsp;values&nbsp;("&nbsp;+&nbsp;list.get(1).getId()+",&nbsp;"+list.get(1).getUserName()+",&nbsp;"+list.get(1).getPassword()+")");for(int&nbsp;i&nbsp;=&nbsp;2;&nbsp;i&nbsp;<&nbsp;list.size();&nbsp;i++){&nbsp;&nbsp;&nbsp;&nbsp;sql.append(",&nbsp;("+&nbsp;list.get(i).getId()+",&nbsp;"+list.get(i).getUserName()+",&nbsp;"+list.get(i).getPassword()+")");//}sql.append(";");&nbsp;&nbsp;&nbsp;ResultSet&nbsp;rs&nbsp;=&nbsp;stmt.executeQuery(sql);&nbsp;rs.close();&nbsp;stmt.close();&nbsp;&nbsp;con.close();

蝴蝶不菲

Class.forName("com.mysql.jdbc.Driver");Connection&nbsp;conn&nbsp;=&nbsp;DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/kxh?useServerPrepStmts=false&rewriteBatchedStatements=true","root",&nbsp;"root");&nbsp;conn.setAutoCommit(false);PreparedStatement&nbsp;ps&nbsp;=&nbsp;conn.prepareStatement("insert&nbsp;into&nbsp;user_table(id,userName,passWord)&nbsp;values(?,?,?)");List<User>&nbsp;list=new&nbsp;ArrayList<User>();//你的listfor&nbsp;(User&nbsp;user:list)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;ps.setInt(1,&nbsp;user.getId());&nbsp;&nbsp;&nbsp;&nbsp;ps.setString(2,&nbsp;user.getUsername());&nbsp;&nbsp;&nbsp;&nbsp;ps.setString(3,&nbsp;user.getPassword());&nbsp;&nbsp;&nbsp;&nbsp;ps.addBatch();&nbsp;//加入批量}ps.executeBatch();//执行批量conn.commit();//提交事务&nbsp;ps.close();conn.close();

绝地无双

用JDBC,加驱动建连接这是Java程序员的基本功之一。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Oracle
Java