增加表的数据一次代码只能增加一次 自己偷了懒 试了一下;
需要自定义工具类JDBCUtils;来链接数据库
代码如下:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
public class Zidongzengjia {
	public static void main(String[] args) throws SQLException {
		Connection con = JDBCUtils.getConnection();
		int i=1;
		Scanner s=new Scanner(System.in);
		System.out.print("你想要添加几次请输入:   ");
		int x = s.nextInt();
		while(i<=x){
		System.out.print("输入名字:    ");
		String name = s.next();
		System.out.print("输入价格:    ");
		int price= s.nextInt();
		System.out.print("输入描述:    ");
		String cause = s.next();
		PreparedStatement pro = con.prepareStatement("INSERT INTO pay (pname,pmoney,cause) VALUES (?,?,?)");
		pro.setString(1, name);
		pro.setInt(2, price);
		pro.setString(3, cause);
		int row = pro.executeUpdate();
		if(row>0){
			System.out.println("添加名字为"+name+"的数据成功!");
			if(i==x){
				System.out.println("已经添加完毕可在数据库中查看");
				break;
			}else{
				i++;
			}
		}
		}
	}
}
JDBC自定义工具:
package cn.com.yin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
		private JDBCUtils(){}
		private static Connection con;
		static{
			try {
				Class.forName("com.mysql.jdbc.Driver");
				//2获得连接  对象
				String url ="jdbc:mysql://localhost:3306/student";
				String username="root";
				String password="root";
				con = DriverManager.getConnection(url, username, password);
			} catch (Exception e) {
				throw new RuntimeException("数据库连接失败");
			}
		//类 。方法	
		}
		//定义静态方法  返回数据库的连接
		public static Connection getConnection(){
			return con;
		}
		//关资源
		public static void close(Connection con, Statement stat){
			if(stat!=null){
				try {
					stat.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(con!=null){
					try {
						con.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		public static void close(Connection con, Statement stat,ResultSet rs){
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}
				if(stat!=null){
					try {
						stat.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(con!=null){
						try {
							con.close();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
原文:https://www.cnblogs.com/yinziqiang0909/p/10443270.html