JavaDB:JDBC-INSERT-UPDATE-SQLInjection

From Juneday education
Jump to: navigation, search

Full frontal - Code up-front!

Just some code examples using PreparedStatement:

public PreparedStatement preparedStatement(String sql) throws SQLException {
  return con.prepareStatement(sql);
}

In a different part of the application:

/**
 * Updates a municipality's https flag
 * @param name The name of the municipality
 * @param https The new value of the https flag
 * @return The number of updated rows or 0 if no rows were updated or -1 if something went to hell
*/
public int updateHTTPSbyName(String name, boolean https) {
  String sql = "UPDATE municipalities SET HTTPS=? WHERE name= ?";
  int result = 0;
  try {
    PreparedStatement pStm = db.preparedStatement(sql);
    pStm.setInt(1, (https ? 1 : 0) );
    pStm.setString(2, name);
    result = pStm.executeUpdate();
    return result; // number of rows updated
  } catch (SQLException e) {
    System.err.println("Error creating prepared stm: "+e.getMessage());
    return -1; // Something went wrong - We should throw an exception if this is critical
               // but this is just example code, so we don't
  }
}

Introduction

This chapter introduces you to how to perform INSERT, DELETE and UPDATE using JDBC (and a short introduction to SQL Injections).

Requirements

In order to fully understand this chapter, we assume you have basic knowledge of SQL and SQLite. If you feel that you need to freshen up on SQL, we recommend our book Introduction_to_Databases. We also assume you have a solid understanding of Java (interfaces, classes, exceptions etc). If you need to refresh your Java basics, see our book Programming with Java.

Lecture slides and videos

English videos

No English videos yet, but we are planning to make some soon!

Swedish videos

Links

External links

Where to go next

After this chapter you should move on to the Exercise - JDBC-INSERT-UPDATE-SQLInjection chapter.

Previous chapter (Introduction_to_JDBC) | Next chapter (Exercise - JDBC-INSERT-UPDATE-SQLInjection)