简体   繁体   English

如何使用Java从mysql获取数据

[英]How to get data from mysql using java

I can't figure out how to get data from mySQL. 我不知道如何从MySQL中获取数据。 This is my first attempt at using java to interact with mysql and its quiet confusing. 这是我第一次尝试使用Java与mysql进行交互,并使其产生混乱。

What I want this piece of code to do is go into my db find "table" then get the value of "column" where the persons' name = "name". 我想要这段代码要做的是进入我的数据库,找到“表”,然后获取“列”的值,其中人的名字=“名字”。 Here's what I have 这就是我所拥有的

public boolean useProspawn(String column, String name ){
        //long time = System.currentTimeMillis()/1000;
        //long prevTime = 0;

        Calendar calendar = Calendar.getInstance();
        java.sql.Timestamp curTime = new java.sql.Timestamp(calendar.getTime().getTime());
        java.sql.Timestamp prevTime;
        long diff = 0;
        long duration = 0;
        try {
            PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT ? FROM accounts WHERE name = ?");
            ps.setString(1, column);
            ps.setString(2, name);
            ResultSet rs = ps.executeQuery();
            prevTime = rs.getTimestamp(column);
            ps.close();
            rs.close();

        } catch (SQLException e) {
            System.out.println("Error getting player's pro spawner times:"); //THIS IS THE ERROR THAT IS GETTING THROWN INTO THE CMD CONSOLE
            System.out.println(e);

            return false;
        }

       diff = curTime.getTime() - prevTime.getTime();
       duration = TimeUnit.MILLISECONDS.toHours(diff);
       if (duration < 24){
           return false;
       } else {
           try {
            String psStatement = "UPDATE accounts SET ?=? WHERE name=?";
            PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(psStatement);
            ps.setString(1, column);
            ps.setTimestamp(2, curTime);
            ps.setString(3,name);
            ResultSet rs = ps.executeQuery();
            ps.close();
            rs.close();
            return true; // can use spawner
        } catch (SQLException e) {
            System.out.println("Error updating player's pro spawner times..");
            return false;
        }

       }

    }

I noticed that I'm getting the error at my "try/catch" statement because the only thing that is getting output in to cmd is the "error getting..." statement. 我注意到我在“ try / catch”语句中遇到了错误,因为唯一输入到cmd的东西就是“ error Getting ...”语句。 Any ideas whats going on? 有什么想法吗?

One obvious error is that the way you use the ResultSet for the select is not correct. 一个明显的错误是您使用ResultSet进行选择的方式不正确。 Before you can get the first row values, you must call next first on the ResultSet. 在获取第一行值之前,必须在ResultSet上首先调用next。

ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
}

JDBC Basic JDBC基础

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

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