【Insert】使用java对mysql数据库进行插入操作

//插入100条数据
package
database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class InsertMysql { public static void main(String[] args) { Connection conn = null; PreparedStatement stmt = null; try {//加载驱动 Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try {//获取连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mydata","root",""); } catch (SQLException e) { e.printStackTrace(); } try {//根据连接获取一个预执行sql语句的对象 stmt = conn.prepareStatement("insert into dept values(?,?,?)"); } catch (SQLException e) { e.printStackTrace(); } try {//执行sql语句 for(int i = 0;i<100;i++){ stmt.setInt(1, i); stmt.setString(2, i+""); stmt.setString(3, i+""); stmt.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } try {//关闭连接 conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/Jourly/p/5614313.html