Java中的SQL查询:(JDBC)如何使用SELECT语句? [英] SQL queries in Java: (JDBC) How to use the SELECT statement?

查看:1397
本文介绍了Java中的SQL查询:(JDBC)如何使用SELECT语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MysqlDatabase

这是我要连接到数据库的查询.

This is my query to connect to my database.

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

我在netbeans控制台中工作.当我想用Spel_Naam显示表Speler的记录时.

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

在控制台中,我想键入表Spel的主键,然后向我显示控制台中表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. How can I do this.

WHERE Spel_Naam = ?

问号必须是我输入的名称

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

select语句正确吗?我想在控制台中键入Spel_Naam,然后它必须连接到数据库并向我提供表Speler的记录.我该怎么办?

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;

}

推荐答案

使用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();

附加说明:作为另一种选择,SQL查询的连接是完成同一任务的不安全方法.有关更多信息,请参见文章.

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.

这篇关于Java中的SQL查询:(JDBC)如何使用SELECT语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆