1

I am using PreparedStatement to make alterations to my database but I am getting an SQL error because it is adding ' ' to the SQL expression. How can prevent it from putting it?

JdbcConnection connection = (JdbcConnection) database.getConnection();
            DatabaseMetaData metadata;
            metadata = connection.getMetaData();
            String[] types = {"TABLE"};
            ResultSet rs = metadata.getTables(connection.getCatalog(), null, "%", types);
            PreparedStatement s = connection.prepareStatement(sqlStatement);


            //if the user chose to use a suffix
            if (this.getSuffix() != null) {
                while (rs.next()) {
                    String tableName = rs.getString(3);
                    if (tableName.endsWith(this.getSuffix())) {
                        tablesFound = true;
                        if (!checkColumnsExists(s, tableName)) {
                            s.setString(1,tableName);
                            s.setString(2,this.getColumnName());
                            s.setString(3,this.getColumnType());

                            if(this.after!=null){
                                s.setString(4,this.after);
                                if(this.defaultValue!=null){
                                    s.setString(5,this.defaultValue);
                                }
                            }
                            else{
                                if(this.defaultValue!=null){
                                    s.setString(4,this.defaultValue);
                                }
                            }
                            s.executeUpdate();
                            columnsAdded = true;
                        }
                    }
                }
            }

This is the expression that PreparedStatement executes

 ALTER TABLE 'saft_2017_2_111_nc_transactions' ADD COLUMN 'testeRegex' 'varchar(250)'
Fabio
  • 343
  • 1
  • 6
  • 17
  • 2
    Database objects such as table and column names can't be bound via a prepared statement, which would represent a security hole. Instead, you'll have to concatenate your query together, but be very cautious when doing this. – Tim Biegeleisen Apr 09 '21 at 13:47
  • @Tim Biegeleisen cautious how? – Fabio Apr 09 '21 at 14:23
  • Well if you concatenate your alter statement together using inputs from the outside, you leave open the possibility of SQL injection, which is precisely what prepared statements prevent. – Tim Biegeleisen Apr 09 '21 at 15:29
  • Só how should I concatenate? Inside the while loop? – Fabio Apr 09 '21 at 15:54

0 Answers0