JAVA解决插入数据库时遇到的引号问题

今天在论坛上看到了问题,自己也总结一下先:
帖子如下:http://topic.csdn.net/u/20081204/01/c45bda75-e429-4600-8924-7f2c7d67406e.html?seed=1788175006
高手们已经做了解答,基本有两个解决方法
一、是采用PreparedStatement,然后setString

  1. Stringsql= "updateinterface_customersetPK_CORP=?,DEF1=?" ;
  2. PreparedStatementpstmt=con.prepareStatement(sql);
  3. pstmt.setString(1,customers[i].getPk_corp());
  4. pstmt.setString(2,customers[i].getDef1());
  5. pstmt.executeUpdate();


二、对有引号的值转換:

  public static String getSafeSQL(String inStr) {

		String result = "";
		try {
			inStr = inStr.trim();
			char c;
			int strLen = inStr.length();
			for (int i = 0; i < strLen; i++) {

				c = inStr.charAt(i);

				switch (c) {
				case '\'':
					result = result + "''";
					break;
				case '\\':
					result = result + "\\\\";
					break;
				default:
					result = result + String.valueOf(c);
					break;
				}

			}

		} catch (Exception e) {
			return "";
		}

		return result;
	}
 

 

你可能感兴趣的:(java,sql,C++,c,C#)