简体   繁体   中英

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

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;

}

Use PreparedStatement s:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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