简体   繁体   English

Java中的SQL查询:(JDBC)如何使用SELECT语句?

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

MysqlDatabase 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. 我在netbeans的控制台工作。 When I want to show the records of table Speler with the Spel_Naam. 当我想用Spel_Naam显示表Speler的记录时。

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. 在控制台中,我想键入表Spel的主键,然后它显示控制台中Speler表的记录。 How can I do this. 我怎样才能做到这一点。

Like WHERE Spel_Naam = ? 喜欢WHERE Spel_Naam = ?

The question mark need to be the name that I typed in 问号必须是我输入的名称

Is the select statement correct? select语句是否正确? 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. 我想在控制台中键入Spel_Naam然后它必须连接到数据库并给我表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: 使用PreparedStatement

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. 附加说明:作为另一种选择,SQL查询的连接是执行相同任务的不安全方式。 Refer to this article for more info. 有关详细信息,请参阅文章。

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

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