日期:2014-05-16  浏览次数:20472 次

java 连接数据库错误总结
昨天第一天接到任务,把数据库中name相同的行,将第一条中列不为空的内容复制到第二条为空的对应位置。
public static void main(String[] args) {
		// TODO Auto-generated method stub
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/brew_operation_db?characterEncoding=UTF-8";
		String userName = "root";
		String password = "123";
		ArrayList<String> Imagepath = new ArrayList<String>();
		ArrayList<String> name = new ArrayList<String>();
		ArrayList<Integer> id = new ArrayList<Integer>();
		ArrayList<Integer> ids = new ArrayList<Integer>();
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, userName, password);
			Statement statement = conn.createStatement();
			String sql = "select * from brew group by name having count(*)>1";
			ResultSet rs = statement.executeQuery(sql);
			while(rs.next()){
				name.add(rs.getString("name"));
				id.add(rs.getInt("id"));
				Imagepath.add(rs.getString("Imagepath")) ;
			}
			rs.close();
			statement.close();
			for (int j = 0; j < id.size(); j++) {
				String sqla = "select * from brew where name = '"+name.get(j)+"' and id <> "+id.get(j);
				Statement statement1 = conn.createStatement();
				ResultSet rs1 = statement1.executeQuery(sqla);
				if(rs1.next()){
					ids.add(rs1.getInt("id"));
				}
			}
			for (int i = 0; i < ids.size(); i++) {
				String sqlb = "update brew set Imagepath = '"+Imagepath.get(i)+"' where id = "+ids.get(i);
				Statement statement2 = conn.createStatement();
				int s = statement2.executeUpdate(sqlb);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
		
	}

代码很不完善,遇到很多问题,最难是最后问杨哥的,原来是编码,一定要记住!
String url = "jdbc:mysql://localhost:3306/brew_operation_db?characterEncoding=UTF-8";