文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>JDBC处理转义字符专题[整理]

JDBC处理转义字符专题[整理]

时间:2010-06-30  来源:hkebao

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("'","''");
正则替换处理掉即可!

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载