如何获取sqlite表中的行/记录总数

时间:2015-04-22 15:43:58

标签: c++ qt sqlite

我想知道如何获取sqlite表中的行/记录总数并将其分配给变量。我这样做了;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.BorderFactory;
import javax.swing.JLabel;

public class View extends JLabel {
    private Snake snake;
    private Fruit fruit;
    private Game game;

    public View(int size, Game g) {
        int W = Game.SIZE * Snake.SIZE;
        int H = Game.SIZE * Snake.SIZE;
        this.setOpaque(true);
        this.setBounds((Game.WIDTH-W)/2, (Game.HEIGHT-H)/2, W, H);
        this.setBackground(Color.WHITE);
        this.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        snake = new Snake(Snake.SIZE, Snake.SIZE);
        fruit = new Fruit();
        game = g;

    }

    public void start() {
        boolean flag = true;
        snake.start();

        while(flag) {
            snake.move();
            repaint();
            try {
                Thread.sleep(100);
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void move(int dir) {
        snake.move(dir);
    }

    public void doDrawing(Graphics2D g) {
        int s = snake.SIZE;
        int fx = fruit.getX();
        int fy = fruit.getY();
        g.setColor(Game.SNAKE_COLOR);
        Snake sn = snake;
        boolean flag = true;
        while(flag) {
            g.fillRect(sn.getX(), sn.getY(), s, s);
            if(sn.hasTail()) {
                sn = sn.getTail();
            }
            else flag = false;
        }

        g.setColor(Game.FRUIT_COLOR);
        g.fillRect(fx, fy, s, s);

        if(snake.getX() == fx && snake.getY() == fy) {
            snake.ate();
            fruit.create();
        }
    }

    public void paint(Graphics g) {
        game.repaint();
        Graphics2D d = (Graphics2D) g;
        doDrawing(d);
    }
}

但问题是,如何将结果分配给变量? 我试过了;

    QSqlQuery query("SELECT COUNT(*) FROM class1_bills");

int rows = query.seek(0);

是的,我知道这样做只会访问表中字段位置 0 的记录。但似乎Qt的查询方法仅用于访问现场位置的特定记录。如果我错了,请纠正我。那么如何获得表中的总行数?

2 个答案:

答案 0 :(得分:3)

查询返回单个列和单个行。

只需阅读该值:

query.first();
count = query.value(0).toInt();

答案 1 :(得分:0)

这很简单,就像任何其他查询一样:

int rows = 0;
QSqlQuery query("SELECT COUNT(*) FROM class1_bills");
if (query.next()) {
    rows = query.value(0).toInt();
}
// Do something with rows