Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29307644
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Java

2010-06-30 22:28:02

1.明确表结构与所要保存的内容解决方案:

package cn.vo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123");
            String contentString = "select name from a where a='test' and b='e'";
            PreparedStatement statement2 = conn.prepareStatement("insert into a(`a`) values(?)");
            statement2.setString(1, contentString);
            statement2.executeUpdate();
            statement2.close();
            statement2 = null;
            conn.close();
            conn = null;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}


说明:可以使用PreparedStatement 处理!

第二种情况:动态组成的SQL语句
不用这个方法直接对字符串做一次转义处理


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123");
            String contentString = "select name from a where a='test' and b='e'";
            Statement statement = null;
            statement = conn.createStatement();
            contentString=contentString.replace("'","''");
            String sqlString = "insert into a(`a`) values(\'"+contentString+"\')";
            System.out.println(sqlString);
            statement.execute(sqlString);
            conn.close();
            conn = null;
        } catch (SQLException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }
        
    }
}


说明:
对有特殊字符的变量做一次处理
contentString=contentString.replace("'","''");
正则替换处理掉即可!

阅读(2193) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~