简体   繁体   English

Java&MySql-如何在执行查询前对其进行转义

[英]Java & MySql - How to escape query before execute it

I'm using Java for a web application, and I'm working with a MySql database. 我正在将Java用于Web应用程序,并且正在使用MySql数据库。 I need to escape the query before execute it. 我需要先执行查询后对其进行转义。 This is my actual code : 这是我的实际代码:

db_result=mydb.selectQuery("SELECT nickname FROM users WHERE nickname='"+log_check_user+"' AND password='"+log_check_pass+"'");

public Vector selectQuery(String query) {
  Vector v = null;
  String [] record;
  int colonne = 0;
  try {
     Statement stmt = db.createStatement();
     ResultSet rs = stmt.executeQuery(query);
     v = new Vector();
     ResultSetMetaData rsmd = rs.getMetaData();
     colonne = rsmd.getColumnCount();

     while(rs.next()) {
        record = new String[colonne];
        for (int i=0; i<colonne; i++) record[i] = rs.getString(i+1);
        v.add( (String[]) record.clone() );
     }
     rs.close();
     stmt.close();
  } catch (Exception e) { e.printStackTrace(); errore = e.getMessage(); }

  return v;
 }

I need this, as you can believe, to avoid the SQL Injection problem! 正如您所相信的,我需要这样做来避免SQL注入问题! How can I do it? 我该怎么做?

Use a prepared statement : 使用准备好的语句

Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. 有时,使用PreparedStatement对象将SQL语句发送到数据库更方便。 This special type of statement is derived from the more general class, Statement ... 这种特殊类型的语句是从更通用的类Statement派生的。

If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead. 如果要多次执行一个Statement对象,通常可以减少执行时间,而改用PreparedStatement对象。

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. PreparedStatement对象的主要特征在于,与Statement对象不同,它在创建时会被赋予一条SQL语句。 The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. 这样做的好处是,在大多数情况下,此SQL语句会立即发送到DBMS,并在此进行编译。 As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. 结果, PreparedStatement对象不仅包含SQL语句,还包含已预编译的SQL语句。 This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first... 这意味着当执行PreparedStatement时,DBMS可以只运行PreparedStatement SQL语句而不必先对其进行编译...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM