SQL queries in Java: (JDBC) How to use the SELECT

2019-09-01 16:32发布

问题:

MysqlDatabase

This is my query to connect to my database.

SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam 
FROM speler 
WHERE Spel_Naam = ?

I work in the console of netbeans. When I want to show the records of table Speler with the Spel_Naam.

In the console I want to type a primary key of the table Spel and then it shows me the records of the table Speler in the console. How can I do this.

Like WHERE Spel_Naam = ?

The question mark need to be the name that I typed in

Is the select statement correct? I want to type the Spel_Naam in the console and then It must connect to the database and give me the records of table Speler. How can I do this?

public class SpelerMapper
{
    private final static String LEES_SPELERS_SQL = "SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam FROM speler WHERE Spel_Naam = ?";

    public List<Speler> geefSpelers()
    {

        List<Speler> spelerLijst = new ArrayList<Speler>();

        Statement statement;
        Connection connection = PersistentieController.getInstance().getConnection();
        try
        {
            statement = connection.createStatement();

            // query database
            ResultSet resultSet = statement.executeQuery(LEES_SPELERS_SQL);

            while (resultSet.next())
            {

                String naam = resultSet.getString("naam");
                String kleur = resultSet.getString("kleur");
                int sector = resultSet.getInt("sector");
                int aantalZilverstukken = resultSet.getInt("aantalZilverstukken");

                Speler speler = new Speler(naam ,kleur, sector , aantalZilverstukken);
                spelerLijst.add(speler);
            }
            statement.close();
            return spelerLijst;
        } catch (SQLException e)
        {
            e.printStackTrace();
        }

    return null;

}

回答1:

Use PreparedStatements:

String LEES_SPELERS_SQL = "SELECT ... WHERE Spel_Naam = ?";
PreparedStatement prepStmt = con.prepareStatement(LEES_SPELERS_SQL);
prepStmt.setString(1, naam); 

ResultSet rs = prepStmt.executeQuery();

Additional note: while being another option, concatenation of the SQL query is an unsafe way of doing the same task. Refer to this article for more info.