Simple use of SQLite database in QT

Source: Internet
Author: User

Code: mian. cpp

 

# Include <qtcore/qcoreapplication> <br/> # include <qtsql> <br/> # include <qdebug> <br/> int main (INT argc, char * argv []) <br/>{< br/> qcoreapplication A (argc, argv); <br/> qsqldatabase DB = qsqldatabase: adddatabase ("qsqlite "); <br/> dB. setdatabasename ("/tmp/My. DB "); <br/> If (! DB. open () <br/>{< br/> qdebug () <"Open Database failed ---" <dB. lasterror (). text () <"/N"; <br/> return-1; <br/>}< br/> qsqlquery query; <br/> bool OK = query.exe C ("CREATE TABLE if not exists people (ID integer primary key autoincrement," <br/> "name varchar (20) not null, "<br/>" Age integer null) "); <br/> If (OK) <br/>{< br/> qdebug () <"ceate table partition success/N"; <br/>}< br/> else <br/>{< br/> qdebug () <"ceate table partition failed/N"; <br/>}< br/> for (INT I = 0; I <3; ++ I) <br/>{< br/> query. prepare ("insert into people (ID, name, age) values (: ID,: name,: Age)"); <br/> query. bindvalue (": Name", qstring ("Smith _ % 1 "). arg (I + 1); <br/> query. bindvalue (": Age", 20 + I * 5); <br/> query.exe C (); <br/>}</P> <p> // qsqlquery query; <br/> query.exe C ("select ID, name, age from people"); <br/> while (query. next () <br/>{< br/> qdebug () <"People (" <query. value (0 ). toint () <") Name:" <query. value (1 ). tostring () <"Age:" <query. value (2 ). toint (); <br/>}< br/> return a.exe C (); <br/>}

 

SQL. Pro:

Qt + = core SQL <br/> QT-= GUI <br/> Target = SQL <br/> config + = console <br/> config-= app_bundle <br/> libs + =-lsqlite3 <br/> template = app </P> <p> sources + = Main. CPP

 

Compile, run, and output:

Ceate table partition success

People (1) Name: "smith_1" Age: 20

People (2) Name: "smith_2" Age: 25

People (3) Name: "smith_3" Age: 30

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.