i am new to sqlite and I just recently installed it. I am familar with mysql but I need to use sqlite as I am using it for a C++ application that I am going to create.
Question 1:
I type this at my command line terminal
root#ubuntu:/home/baoky/version1.2/Assignment 2# sqlite abeserver.db
then I saw this output
sqlite>
So i type .h and i see a list of help commands
But i wanna create a table
sqlite> .databases
seq name file
--- --------------- ----------------------------------------------------------
0 main /home/baoky/version1.2/Assignment 2/abeserver.db
1 temp /var/tmp/sqlite_hjT3FEefcAHRPhn
in my main database
How do i execute this sql command at terminal level
CREATE TABLE abe_account (
username TEXT,
name TEXT,
department TEXT,
password TEXT
);
Question 2:
How do I insert record into the table abe_account using C++
Question 3:
How do I retrieve records from table abe_account and assign it to a string using C++
Sorry I tried google around and search around stack overflow, I am still confused with the usage, if its mysql, it would be much simple for me.
Question 2:
Question 3:
Let me google it for you, friend: An Introduction To The SQLite C/C++ Interface.
If you are using the sqlite terminal, you can just type SQL there, and it will be executed.
A typical cycle of work from your C++ code will look something like this:
sqlite3 * db;//database
sqlite3_stmt * stmt;//sql statement
sqlite3_open( "database.db", & db );//opening database
sqlite3_prepare( db, "SELECT something FROM something else;", -1, &stmt, NULL );//preparing the statement
sqlite3_step( stmt );//executing the statement
while( sqlite3_column_text( stmt, 0 ) )
{
char * str = (char *) sqlite3_column_text( stmt, 0 );///reading the 1st column of the result
//do your stuff
sqlite3_step( stmt );//moving to the next row of the result
}
sqlite3_finalize(stmt);
sqlite3_close(db);
You can easily google the functions to learn about their arguments and what they do in-detail.
To create a new database, just connect to it:
$ sqlite3 your_database_file
This will create your database in the file your_database_file. If this file already exists, the command will open it.
Then you can execute CREATE TABLE or any other SQL.
Related
I´m having the following code that insert a row into mysql database and return the inserted id:
/*
* Execute the statement
*/
std::string sql = "INSERT INTO TABLE (A, B, C) VALUES (1, 2, 3)";
sql::Statement *stmt;
stmt = connection->createStatement();
stmt->execute(sql);
/*
* Get the returned id
*/
stmt = connection->createStatement();
sql::ResultSet *res = stmt->executeQuery("SELECT ##identity AS id");
res->next();
model.modelId = res->getInt64("id");
My questions are:
Do I really need to call connection->createStatement() again ?
I think this may overload the code, as I need to call twice the database.
Is there a way to optimize this code ?
Is there other way to get the last inserted id ?
Thanks for helping.
Just for the reference, ##identity is MSSQL-specific system function, that also returns last-insert id but for MSSQL, not for MySQL.
To get last-insert id in MySQL, since you have asked specifically for MySQL, you need to change your SELECT statement to following:
SELECT LAST_INSERT_ID() AS id;
Also, since stmt->execute() and stmt->executeQuery() methods take String, as input argument, I am sure that you don't need to connection->createStatement() again. Just to confirm, I just googled it and found this link.
Please note that this answer is specifically for MySQL, as this question is about MySQL. Hope it helps.
I'm using pro c/c++ in a unix environment. Inside a c function I create a simple select statement which is not inside a loop and autocommit is disabled.
This is the dynamic sql;
char sql_statement[200];
int num1, num2;
...
snprintf(sql_statement, sizeof(sql_sattement), "select column1, column2 from '%s' where num = '%d' and code_cfg = '%d'", "customer", 0, 0);
exec sql prepare instruction_to_execute from :sql_statement;
exec sql declare crs cursor for instruction_to_execute;
exec sql open crs;
exec sql fetch crs into :num1, :num2;
...
Executing this code gives me ORA-01002 error. As I said before, this code is not inside a loop and autocommit is off.
But if I write this code statically, works fine. Below the code:
EXEC SQL
SELECT column1, column2
INTO :num1, :num2
FROM CUSTOMER
where num = 0
AND code_cfg = 0;
SQL instruction is simple. For my understanding this code should be executed fine.
In SO I found some answers:
ORA-01002: fetch out of sequence C++
ORA-01002: fetch out of sequence
Hibernate error “ORA-01002” when persisting entity with custom Sequence Generator
ORA-01002: fetch out of sequence
java.sql.SQLException: ORA-01002: fetch out of sequence
I know many questions were asked around the issue I have, I spent along time trying to implement all kinds of solutions but didn't help.
I am trying to read a .db file using Qt SQLite platform.
windows 8 Qt 5.3.2
Opening the db file in DB browser for SQLite and executing my simple query succeeds:
SELECT Name FROM Person ORDER BY Name
and there is a list of 10 rows at the output.
I would like to do it throw Qt. my code:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:\mydb.db");
if(db.open())
{
QSqlQuery qry(db);
if(qry.exec("SELECT Name FROM Person ORDER BY Name"))
{
while(qry.next())
{
//some code
}
}
QSqlError e;
QString s,d;
e = qry.lastError();
s = e.databaseText();
d = e.driverText();
}
this code falls, the qry.exec command returns false, and last error is "no such table; person"
Running the command: QStringList tables = db.tables(QSql::AllTables);
after the Data Base is open shows that there is one table in Data Base called: sqlite_master.
trying to replace the query within the exec command with the query: "SELECT tbl_name FROM sqlite_master WHERE type = 'table'"
as says at: http://www.sqlite.org/faq.html#q7
causes the exec command to return true but qry.next() returns false already from the first iteration, although I have 5 tables in my data base.
I would be great full to how ever can me with my problem!
thanks!!!
You should specify the path to the database file correctly. Instead of C:\mydb.db you should use C:\\mydb.db or C:/mydb.db.
That's because the compiler uses \ as an escape character in strings (for things like \t, \n or \r). so \\ is actually turned into \.
I need to insert a blob in o oracle database. I am using c++ and ODBC library.
I am stucked at the insert query and update query .It is abstract for me how to make an blob insert query.
I know how to make an query for a non blob column.
My table structure is :
REATE TABLE t_testblob (
filename VARCHAR2(30) DEFAULT NULL NULL,
apkdata BLOB NULL
)
I found an exemple on insert and update :
INSERT INTO table_name VALUES (memberlist,?,memberlist)
UPDATE table_name SET ImageFieldName = ? WHERE ID=yourId
But these structure of querys or abstract to me . What should memberlist be ? why is there "?" where are the values to be inserted ?
Those question marks means that it is PreparedStatement. Such statements are good for both server and client. Server has less work because it is easier to parse such statement, and client do not need to worry about SQLInjection. Client prepares such query, builds buffer for input values and calls it.
Also such statement is executed very quick compared to "normal" queries, especially in loops, importing data from csv file etc.
I don't know what ODBC C++ library you use while ODBC is strictly C library. Other languages like Java or Python can use it too. I think the easiest is example in Python:
cursor = connection.cursor()
for txt in ('a', 'b', 'c'):
cursor.execute('SELECT * FROM test WHERE txt=?', (txt,))
Of course such PreparedStatement can be used in INSERT or UPDATE statements too, and for your example it can look like:
cursor.execute("INSERT INTO t_testblob (filename, apkdata) VALUE (?, ?)", filename, my_binary_data)
I generate an sqlite3 database file (call it db.sl3; invoked interactively as $ sqlite3 db.sl3 from a shell) from within the sqlite3 commandline program, for instance
create table people (
id integer,
firstname varchar(20),
lastname varchar(20),
phonenumber char(10)
);
insert into people (id, firstname, lastname, phonenumber) values
(1, 'Fred', 'Flintstone', '5055551234');
insert into people (id, firstname, lastname, phonenumber) values
(2, 'Wilma', 'Flintstone', '5055551234');
insert into people (id, firstname, lastname, phonenumber) values
(3, 'Barny', 'Rubble', '5055554321');
I am trying to use this in a program I have written which uses the sqlite3 C API; however, whenever I attempt to open up the database file in the C program using either
sqlite3* db;
rc = sqlite3_open( "db.sl3", &db );
or
rc = sqlite3_open_v2( "db.sl3", &db, SQLITE_READONLY, 0 );
followed by a query where the SQL is contained in the following string
std::string sqlCmd = "select * from sqlite_master where type='table' order by name";
to the sqlite3_get_table wrapper interface invoked as follows
rc = sqlite3_get_table( db, sqlCmd.c_str(), &result, &numRows, &numCols, &errorMsg );
The return code (rc) is 0 in either case implying that there was no problem with the operation but there are no tables entries recorded in the result variable. I have tried all sorts of pathing issues (e.g., using absolute paths to the db file, relative, only in the invocation directory, etc.) to no avail. Also, when I reopen the database file with the sqlite3 commandline program I can see the tables and their entries. As an aside, if I open, create and insert the lines into the table in the C program I can access them fine.
Any help would be much appreciated. Am I not properly initializing things?
By default sqlite3_open will create the database if it does not exist (equivalent with calling sqlite3_open_v2 with flags=SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) - and rc will be SQLITE_OK.
I've tried this test program against a database created using sqlite3 and each time (existing db with people table: full path, relative; existing 0 sized db: full path, relative; nonexistent db: full path, relative) sqlite3_open_v2 behaved as advertised.
Try to do a 'sqlite3 [full_path_to_db]' then run the query and compare the results with what your program or mine does (again with [full_path_to_db]) just in case your sqlite3_open tests created some 0 sized db.sl3 which are then gadly opened by sqlite3_open_v2 .
Hope this helps.