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("'","''");
正则替换处理掉即可!
阅读(2228) | 评论(0) | 转发(0) |