1 | /****************************************************************************
|
---|
2 | **
|
---|
3 | ** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
|
---|
4 | **
|
---|
5 | ** This file is part of an example program for Qt. This example
|
---|
6 | ** program may be used, distributed and modified without limitation.
|
---|
7 | **
|
---|
8 | *****************************************************************************/
|
---|
9 |
|
---|
10 | #include <qapplication.h>
|
---|
11 | #include <qsqldatabase.h>
|
---|
12 | #include <qdatatable.h>
|
---|
13 | #include <qsqlcursor.h>
|
---|
14 | #include <qmessagebox.h>
|
---|
15 |
|
---|
16 | /* Modify the following to match your environment */
|
---|
17 | #define DRIVER "QSQLITE" /* see the Qt SQL documentation for a list of available drivers */
|
---|
18 | #define DATABASE ":memory:" /* the name of your database */
|
---|
19 | #define USER "" /* user name with appropriate rights */
|
---|
20 | #define PASSWORD "" /* password for USER */
|
---|
21 | #define HOST "" /* host on which the database is running */
|
---|
22 |
|
---|
23 | class SimpleCursor : public QSqlCursor
|
---|
24 | {
|
---|
25 | public:
|
---|
26 | SimpleCursor () : QSqlCursor( "simpletable" ) {}
|
---|
27 | protected:
|
---|
28 | QSqlRecord* primeInsert()
|
---|
29 | {
|
---|
30 | /* a real-world application would use sequences, or the like */
|
---|
31 | QSqlRecord* buf = QSqlCursor::primeInsert();
|
---|
32 | QSqlQuery q( "select max(id)+1 from simpletable" );
|
---|
33 | if ( q.next() )
|
---|
34 | buf->setValue( "id", q.value(0) );
|
---|
35 | return buf;
|
---|
36 | }
|
---|
37 | };
|
---|
38 |
|
---|
39 | int main( int argc, char ** argv )
|
---|
40 | {
|
---|
41 | QApplication a( argc, argv );
|
---|
42 |
|
---|
43 | QSqlDatabase * db = QSqlDatabase::addDatabase( DRIVER );
|
---|
44 | db->setDatabaseName( DATABASE );
|
---|
45 | db->setUserName( USER );
|
---|
46 | db->setPassword( PASSWORD );
|
---|
47 | db->setHostName( HOST );
|
---|
48 |
|
---|
49 | if( !db->open() ){
|
---|
50 | db->lastError().showMessage( "An error occured. Please read the README file in the sqltable"
|
---|
51 | "dir for more information.\n\n" );
|
---|
52 | return 1;
|
---|
53 | }
|
---|
54 |
|
---|
55 | if (!db->tables().contains("simpletable")) {
|
---|
56 | QSqlQuery q("create table simpletable(id int, name varchar(20), address varchar(20))", db);
|
---|
57 | }
|
---|
58 |
|
---|
59 | SimpleCursor cursor;
|
---|
60 |
|
---|
61 | QDataTable table( &cursor ); /* data table uses our cursor */
|
---|
62 | table.addColumn( "name", "Name" );
|
---|
63 | table.addColumn( "address", "Address" );
|
---|
64 | table.setSorting( TRUE );
|
---|
65 |
|
---|
66 | a.setMainWidget( &table );
|
---|
67 | table.refresh(); /* load data */
|
---|
68 | table.show(); /* show widget */
|
---|
69 |
|
---|
70 | return a.exec();
|
---|
71 | }
|
---|