3.JDBC插入
一.普通插入
步骤:
1.加载驱动
 2.建立连接
 3.半成品sql语句
 4.生成prepareStatement对象
 5.设置占位符所对应的值,从1开始标号,第一个问号对应第一个标号(例如preStmt.setString(1, “王”+i);对应第一个问号value值
Connection connection = null;
	PreparedStatement preStmt = null;
	try {
		
		Class.forName("com.mysql.cj.jdbc.Driver");
		
		String url = "jdbc:mysql://localhost:3306/tset04"
		+ "?user=root&password=18170021&serverTimezone=UTC";
		connection = DriverManager.getConnection(url);
		String sql = "insert into book(author,publisher,isbn,pubDate"
				+ " ,price) "
					+ "values(?,?,?,?,?)";
		for(int i = 1;i<100;i++){
			preStmt = connection.prepareStatement(sql);	
			preStmt.setString(1, "王"+i);
			preStmt.setString(2,"电子"+i);
			preStmt.setString(3, "125"+i);
			preStmt.setString(4,"2017-5-"+i);	
			preStmt.setDouble(5, i+25);
			
			preStmt.executeUpdate();
		}
		
		preStmt.executeUpdate();	
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally{
		if(preStmt != null)
			try {
				preStmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if(connection != null)
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
	
	}
二.通用插入
思路:函数 public void update(String sql,Object … args) //sql对应于sql语句,而Object…args表示不确定参数,对应于半成品sql语句中的?个数 通过setObject方法处理问号
for(int i = 0;i < args.length;i++){
			preStmt.setObject(i + 1, args[i]);
	}
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号