Menu
  • HOME
  • TAGS

SQlite foreign key logic

Tag: database,sqlite

I am using SQlite and the PK column seems to be auto-incrementing. I am a bit concerned about following approach where I want to normalize the type-column:

Table: Book
id   type  name
...  ...   ...
15    1     Foo
16    2     Bar
...   ...  ...


Table: Type
id  typename
1   magazine
2   novel

What happens, if I recreate the Type-table and the PK-index (="id") changes, e.g. that 1 now refers to novel instead of magazine. So to be more robust, I am thinking about inserting a custom second column that contains the "logical" indices that I refer to:

Table: Book
id   type  name
1    3     Foo
2    4     Bar

Table: Type
id   type  typename
1    3     magazine
2    4     novel

This way my custom type-ids would be independent from the primary keys. I think another advantage of the last approach is that I would not have to re-ask the latest (new) id of a new row, because I would refer to the type column that I know before. This way when I insert the row I already know the "type" id to make references (I am using threads for the database, so reading a value from the database within a method is difficult or not possible (?) - so if I would need the id, I would have to ask the db first).

Is this a legit approach? Or should I directly create a non-incrementing primary key with my "custom id's" that I manage on my own?

Best How To :

As shown in the documentation, you can simply insert the desired values in the PK column:

INSERT INTO Type(id, typename) VALUES(2, 'novel')

And if you never need autoincrement values, you should not use an autoincrementing column in the first place.

IBM Cognos _days_between function not working

mysql,database,date,cognos

The Cognos _days_between function works with dates, not with datetimes. Some databases, like Oracle, store all dates with a timestamp. On a query directly to the datasource, try using the database's functions to get this data instead. When possible, this is always preferable as it pushes work to the database,...

ElasticSearch asynchronous post

database,post,asynchronous,elasticsearch,get

To ensure data is available, you can make a refresh request to corresponding index before GET/SEARCH: http://localhost:9200/your_index/_refresh Or refresh all indexes: http://localhost:9200/_refresh ...

Creating a generic / abstract “DBContext” Class for shared functionality among different DBs

c#,database,generics,inheritance,abstract-class

The key here is to step back and think about the problem from another angle. You are duplicating lots of code because you are creating instances of the database and command classes within the method. So inject them instead: public class SomeDBClass { static DataTable exec_DT(DBConnection conn, DBCommand cmd) {...

Id in database using qt

database,qt,sqlite

The method you're looking for is QSqlQuery::lastInsertId(). To quote the documentation: Returns the object ID of the most recent inserted row if the database supports it. An invalid QVariant will be returned if the query did not insert any value or if the database does not report the id back....

Difference between dba_SEGMENTS and dba_data_files

mysql,sql,database,oracle11g,oracle-sqldeveloper

Oracle uses "logical" und "physical" structures to store the data. For this case: The extents of a segment can be stored in different datafiles, so just summing up can work but must not work see here: http://docs.oracle.com/cd/E11882_01/server.112/e40540/logical.htm#CNCPT301 Plus: Oracle has a "High Water Mark" so even if your segment size...

MySQL: Select several rows based on several keys on a given column

mysql,sql,database

If you are looking to find the records matching with both the criteria here is a way of doing it select `item_id` FROM `item_meta` where ( `meta_key` = 'category' and `meta_value` = 'Bungalow' ) or ( `meta_key` = 'location' AND `meta_value` = 'Lagos' ) group by `item_id` having count(*)=2 ...

want to generate coupon code 5 digit number [duplicate]

sql-server,sqlite

Records in a relational database tables are unordered by nature. therefor, you can simply create a table that has all the values between @First and @Last (0 and 9999 in your case), and then use a random order by when selecting from that table. you can also use a simple...

INNER JOIN Query is not working

ios,sqlite

This is your query, which I understand until the end of the on clause: Select EMPLOYEE.* from EMPLOYEE INNER JOIN DEPARTMENT ON EMPLOYEE.empID = DEPARTMENT.empID =%@",_txtfind.text]; Perhaps you want where clause of some sort? Select e.*, d.col1, d.col2, . . . from EMPLOYEE e INNER JOIN DEPARTMENT d ON e.empID...

error from working in sqllite android

android,sqlite

You are trying to give name group to one of your columns. group itself is a keyword in SQLite so you can't use it. Just change the name of column from group to something else. Check this...

SQL: overcoming no ORDER BY in nested query

sql,sqlite

Use a join instead: SELECT a, b FROM t JOIN (SELECT DISTINCT date FROM t ORDER BY date DESC LIMIT 2) tt on t.date = tt.date; ...

Improving work with SQL DataTime

sql,sql-server,database,tsql

You can do it like this: SELECT IIF(DAY(@A) >= 25, DATEADD(d, 25 - DAY(@A), @A), DATEADD(d, 25, EOMONTH(@A, -2))) Here's a sample fiddle as well: sqlfiddle Note: EOMONTH requires SQL Sever 2012 or above - it returns the End-Of-Month date given a start date and a month offset....

Displaying MySQL results in a single table

php,mysql,database

Try getting all the columns out first, then add it to the sql query, no need to loop the database query. $mark = $_POST['mark']; if (isset($_POST['mark']) && is_array($_POST['mark'])) { echo "<table border='1'>"; echo "<tr>"; for ($i = 0; $i < count($mark); $i++) { echo "<th>" . $mark[$i] . "</th>"; }...

Synchronize local SQLite database with central database

android,performance,sqlite,compare

In your case needs value the situation!! When I have this problems the first questions are... The tables that I want to do 'drop table' have few data? If it's yes the best way is the 'drop table' command. If it's no then you need to use the 'insert' and...

How to use existing SQLite database in swift?

ios,database,xcode,sqlite,swift

First add libsqlite3.dylib to your Xcode project (in project settings/Build Phases/Link Binary with Libraries), then use something like fmdb, it makes dealing with SQLite a lot easier. It's written in Objective-C but can be used in a Swift project, too. Then you could write a DatabaseManager class, for example... import...

Combining two select statements

sql,database,select,where

Try to this var chgAssociationQuery1 = ((from a in sostenuto.PROBLEMS join b in sostenuto.S_ASSOCIATION on a.SERVICEREQNO equals b.FROMSERVICEREQNO join c in sostenuto.Changes on b.TOSERVICEREQNO equals c.SERVICEREQNO where b.FROMSERVICEID == 101001110 && b.TOSERVICEID == 101001109 && a.NAME.Contains(name) select new { ProblemReqNo = a.SERVICEREQNO, ProblemId = a.SERVICEREQID, ChangeReqNo = c.SERVICEREQNO, ChangeId =...

No such table found even though app successfully opens database from assets folder

java,android,sqlite,android-sqlite,sqliteopenhelper

you should copy the .db file from your assets folder to an internal/external storage. You can use following codes, private static String DB_PATH = "/data/data/your package/database/"; private static String DB_NAME ="final.db";// Database name To create a database, public void createDataBase() throws IOException { //If database not exists copy it from...

creating stored procedure in mysql calculate profit from product table

mysql,sql,database,stored-procedures

You forgot the () after the procedure name. Also, you should set a delimiter: DELIMITER // CREATE PROCEDURE sp_profit() BEGIN SET @v1:= (select sum( cost_price * current_stock) from product); SET @v2:= (select sum( selling_price * current_stock) from product); SELECT (@v2 - @v1); END; // ...

Purging Database - Count purged/not-purged tables

mysql,sql,sql-server,database,stored-procedures

The only way to do this is to manually run a count(*) on all of your tables filtering on the particular date field. The reason for this is because one table might have a column "CreatedDate" that you need to check if it's >30 days old, while another might have...

ODBC ISAM_EOF without any reason

c#,database,odbc,cobol

It seems to be Windows UAC reliant. As our application run in compatibility mode, UAC visualization is active and causing may some problems. The reason for this is, that the COBOL databse is a file based database, and the client where are coding for uses these files in ODBC DSN...

sql script to find index's tablespace_name only

sql,database,oracle

SELECT DTA.* FROM DBA_TABLESPACES DTA, dba_indexes DI WHERE DI.TABLESPACE_NAME = DTA.TABLESPACE_NAME AND DI.OWNER ='USER' AND NOT EXISTS (SELECT 'x' FROM DBA_TABLES DTT WHERE DTT.TABLESPACE_NAME = DTA.TABLESPACE_NAME AND DTT.OWNER = DI.OWNER ); ...

ER diagram for booking database

database,database-design

typically, you would store the password as some sort of encrypted hash. It is best if this is one-way, so it cannot be decrypted. When authenticating, you check that you can generate the same hash from the provided password; not decypt what is stored. Your hash should also be "salted"...

Foreign key in C#

c#,sql,sql-server,database

You want create relationship in two table Refer this link http://www.c-sharpcorner.com/Blogs/5608/create-a-relationship-between-two-dataset-tables.aspx...

Pull information from SQL database and getting login errors

php,sql,database

change $username = "'rylshiel_order"; to $username = "rylshiel_order"; and you should be through. You are passing on an extra single quote here. ...

Android SQLite: Fast insert/update

java,android,sqlite

What would be a correct way for overwriting existing row? Specify a conflict resolution strategy, such as INSERT OR REPLACE INTO foo ... If the insert would result in a conflict, the conflicting row(s) are first deleted and then the new row is inserted....

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6

Ideally what you want is a many-to-many relationship between your Shop and Product entities: public class Shop { public int ShopId {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;} } public class Product { public int ProductId {get; set;} public string Name {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;}...

Order by count not sorting the records correctly?

php,mysql,database

Try this SELECT count(receiver_id) as total_receiver FROM gr_group_memberships INNER JOIN gr_group on gr_group_memberships.group_id = gr_group.id GROUP BY gr_group_memberships.receiver_id ORDER BY gr_group_memberships.receiver_id DESC I think it will worked what you want...

Does Maria DB support ANSI-89 join syntax

sql,database,join,syntax,mariadb

Short answer - yes, both options are supported.

sqlite query slow, how to optimize (using linq to entities)

c#,linq,entity-framework,sqlite

The biggest optimization would be changing the Contains to a StartsWith. Which would be equivalent to changing from name like '%search%' to name like 'search%'. Otherwise SQLite can't fully use the indexes you placed on the columns and you are basically searching the whole table. // First Name if (!string.IsNullOrEmpty(firstName))...

SQLite: Individual tables per user or one table for them all?

database,sqlite

In an object oriented language, would you make a class for every user? Or would you have an instance of a class for each user? Having one table per user is a really bad design. You can't search messages based on any field that isn't the username. With your current...

If I export my database with phpmyadmin will it lock my tables or take my database down?

mysql,database,phpmyadmin

The answer is no, tables won't be locked, database won't be down. But, if your database is large and it takes long time to backup it, you can sometimes expect performance degradation(slow SQL queries from your application).

Android unable to write datetime to sqllite database

java,android,sqlite,datetime

For the sqlite issue, you need to have whitespace between column names and types. For example, change TaskEntry.COLUMN_TASK_DUE + "DATETIME, " + to TaskEntry.COLUMN_TASK_DUE + " DATETIME, " + There's a similar problem with almost all of your columns. After fixing the CREATE TABLE SQL, uninstall and reinstall your app...

How to cancel alarm in android after deleting a item in Sqlite database

android,sqlite

Use following code to delete set alarm. Hope this will help you Intent myIntent = new Intent(context,VisitReminderNotificationMessage.class); PendingIntent pendingIntent = PendingIntent.getService(context, id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(VisitReminderNotificationMessage.ALARM_SERVICE); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); ...

Desktop Database with Server without installation

java,database,server,desktop,h2

Like Jayan told me in a comment to my question embedded mode does accept a location to save the data.

How do I access website databases? [closed]

database

In barely any case would you get direct access to another company's database, even if you are affiliated. The most common way would be an API (which might be public or licensed): https://en.wikipedia.org/wiki/Application_programming_interface If the data is publicly available on a website, some do content parsing although this is not...

Retrieve multiple rows from sqlite using where clause Android

android,sqlite

Your condition retrieves 1 record only. If you have more than one record where Emirate = 'Qatar', only the first one is retrieved, because the = condition is satisfied. You need to use the LIKE operator instead of =, to get them all. Replace your query with: String query= "SELECT...

SimpleMembershipProvider WebSecurity.InitializeDatabaseConnection The login from an untrusted domain

asp.net,database,exception,model-view-controller

I think that you are providing in your connection string UserName and password, so you can change from Integrated Security=True to Integrated Security=False and if the user 'DB_9CB321_Szklarnia_admin' has rights to connect it will work. When Integrated Security=True the userID and password will be ignored and attempt will be made...

sqlite: How can results be made unique according to a column

sqlite,android-sqlite

Use DISTINCT for the selection. For more info: http://www.tutorialspoint.com/sqlite/sqlite_distinct_keyword.htm EDIT: Maybe you can select with distinct from the current result. Something like this: SELECT DISTINCT albumTable.album FROM (SELECT albumTable.album, artistTable.artist, songTable.filepath from albumTable inner join artistTable on albumTable.artistID = artistTable.artistID inner join songTable on albumTable.albumID = songTable.albumID ) I don't...

What type of database is the best for storing array or object like data [on hold]

database,node.js,sockets

Redis would probably be fastest, especially if you don't need a durability guarantee - most of the game can be played out using Redis' in-memory datastore, which is probably gonna be faster than writing to any disk in the world. Perhaps periodically, you can write the "entire game" to disk....

echo both users

php,mysql,sql,database,loops

Why don't you just do it in one single query? Just replace the necessary table and column name, and variables/values/parameters to be bind in your query: $query = mysqli_query($conn, "SELECT first_name, last_name, description, role FROM `wp_usermeta` WHERE `first_name` = '$first_name' OR `last_name` = '$last_name' OR `description` = '$description' OR `role`...

How to display db table names

python,sqlite

As you noticed, the database name is cookies.sqlite not cookie.sqlite. Why didn't I get an error? I though python would error out on. con = lite.connect('cookie.sqlite') Connecting to a sqlite database either opens an existing database file, or creates a new one if the database didn't exist....

select data according to Row in Sqlite

android,database,sqlite,android-sqlite

you can do it just like below code public void rec(int _id){ String query = "SELECT * FROM notesDb WHERE PhoneNumber =" + _id; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { String temp_address = c.getString(0); String temp_address1 = c.getString(1); System.out.println(temp_address); System.out.println(temp_address1); } while...

In simple RESTful design, does PATCH imply mapping to CRUD's (ORM's) “update” and PUT to “destroy”+“create” (to replace a resource)?

database,rest,http,orm,crud

Well, Both the actions actually means update, where PUT is full update and PATCH is partial update. In case of PUT you already know the identifier of the resource and the resource already exists, so it is not a create and delete action per se. Infact, you can make do...

Unable to display SQLite data as listview using phonegap

javascript,html,sqlite,cordova

You made a mistake: you used result instead of res: tx.executeSql("SELECT (date) FROM time", [], function (tx, res) { var len = result.rows.length; // <- should be res if (len > 0) { for (var i = 0; i < len; i++) { var a = results.rows.item(i)['date']; // <- should...

Complex SQL with Multiple Joins

mysql,database,join

What I think you should take note of here is that each post has a department and a postType. If you take a step back, you can select all posts that belong to a certain department and a certain postType like this: SELECT p.* FROM posts p JOIN department d...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

Nothing happens when click button

android,sqlite

In protected void onActivityResult(int requestCode, int resultCode, Intent data) { String name = data.getStringExtra("name"); String grup = data.getStringExtra("grup"); today.setToNow(); String timestamp = today.format("%Y-%m-%d %H:%M:%S"); myDb.insertRow(name,timestamp,grup); populateListView(); } You are reading intent data from "name or grup" but in your activity B those string extras never been set correctly....