sql Column with multiple values (query implementation in a cpp file ) - c++

I am using this link.
I have connected my cpp file with Eclipse to my Database with 3 tables (two simple tables
Person and Item
and a third one PersonItem that connects them). In the third table I use one simple primary and then two foreign keys like that:
CREATE TABLE PersonsItems(PersonsItemsId int not null auto_increment primary key,
Person_Id int not null,
Item_id int not null,
constraint fk_Person_id foreign key (Person_Id) references Person(PersonId),
constraint fk_Item_id foreign key (Item_id) references Items(ItemId));
So, then with embedded sql in c I want a Person to have multiple items.
My code:
mysql_query(connection, \
"INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8);");
printf("%ld PersonsItems Row(s) Updated!\n", (long) mysql_affected_rows(connection));
//SELECT newly inserted record.
mysql_query(connection, \
"SELECT Order_id FROM PersonsItems");
//Resource struct with rows of returned data.
resource = mysql_use_result(connection);
// Fetch multiple results
while((result = mysql_fetch_row(resource))) {
printf("%s %s\n",result[0], result[1]);
}
My result is
-1 PersonsItems Row(s) Updated!
5
but with VALUES (1,1,5), (1,1,8);
I would like that to be
-1 PersonsItems Row(s) Updated!
5 8
Can somone tell me why is this not happening?
Kind regards.

I suspect this is because your first insert is failing with the following error:
Duplicate entry '1' for key 'PRIMARY'
Because you are trying to insert 1 twice into the PersonsItemsId which is the primary key so has to be unique (it is also auto_increment so there is no need to specify a value at all);
This is why rows affected is -1, and why in this line:
printf("%s %s\n",result[0], result[1]);
you are only seeing 5 because the first statement failed after the values (1,1,5) had already been inserted, so there is still one row of data in the table.
I think to get the behaviour you are expecting you need to use the ON DUPLICATE KEY UPDATE syntax:
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, order_id)
VALUES (1,1,5), (1,1,8)
ON DUPLICATE KEY UPDATE Person_id = VALUES(person_Id), Order_ID = VALUES(Order_ID);
Example on SQL Fiddle
Or do not specify the value for personsItemsID and let auto_increment do its thing:
INSERT INTO PersonsItems( Person_Id, order_id)
VALUES (1,5), (1,8);
Example on SQL Fiddle

I think you have a typo or mistake in your two queries.
You are inserting "PersonsItemsId, Person_Id, Item_id"
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8)
and then your select statement selects "Order_id".
SELECT Order_id FROM PersonsItems
In order to achieve 5, 8 as you request, your second query needs to be:
SELECT Item_id FROM PersonsItems
Edit to add:
Your primary key is autoincrement so you don't need to pass it to your insert statement (in fact it will error as you pass 1 twice).
You only need to insert your other columns:
INSERT INTO PersonsItems(Person_Id, Item_id) VALUES (1,5), (1,8)

Related

how to insert/update data in sql database using azure databricks notebook jdbc

I got lots of example to append/overwrite table in sql from AZ Databricks Notebook. But no single way to directly update, insert data using query or otherway.
ex. I want to update all row where (identity column)ID = 1143, so steps which I need to taken care are
val srMaster = "(SELECT ID, userid,statusid,bloburl,changedby FROM SRMaster WHERE ID = 1143) srMaster"
val srMasterTable = spark.read.jdbc(url=jdbcUrl, table=srMaster,
properties=connectionProperties)
srMasterTable.createOrReplaceTempView("srMasterTable")
val srMasterTableUpdated = spark.sql("SELECT userid,statusid,bloburl,140 AS changedby FROM srMasterTable")
import org.apache.spark.sql.SaveMode
srMasterTableUpdated.write.mode(SaveMode.Overwrite)
.jdbc(jdbcUrl, "[dbo].[SRMaster]", connectionProperties)
Is there any other sufficient way to achieve the same.
Note : Above code is also not working as SQLServerException: Could not drop object 'dbo.SRMaster' because it is referenced by a FOREIGN KEY constraint. , so it look like it drop table and recreate...not at all the solution.
You can use insert using a FROM statement.
Example: update values from another table in this table where a column matches.
INSERT INTO srMaster
FROM srMasterTable SELECT userid,statusid,bloburl,140 WHERE ID = 1143;
or
insert new values to rows where one of the existing column value matches
UPDATE srMaster SET userid = 1, statusid = 2, bloburl = 'https://url', changedby ='user' WHERE ID = '1143'
or just insert multiple values
INSERT INTO srMaster VALUES
(1, 10, 'https://url1','user1'),
(2, 11, 'https://url2','user2');
In SQL Server, you cannot drop a table if it is referenced by a FOREIGN KEY constraint. You have to either drop the child tables before removing the parent table, or remove foreign key constraints.
For a parent table, you can use the below query to get foreign key constraint names and the referencing table names:
SELECT name AS 'Foreign Key Constraint Name',
OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) AS 'Child Table'
FROM sys.foreign_keys
WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND
OBJECT_NAME(referenced_object_id) = 'PARENT_TABLE'
Then you can alter the child table and drop the constraint by its name using the below statement:
ALTER TABLE dbo.childtable DROP CONSTRAINT FK_NAME;

SQLite increment Integer Primary Key and Unique Constraint conflict

I have a SQLite database.
When writing move rows function, which moves rows from one table to another I need to have a query for incrementing column with name "row" which is INTEGER PRIMARY KEY, but there is an error. It is critical to have indexing with row in my task. The condition in example is WHERE row >= 2 because i am inserting rows from other table into position 2.
"UPDATE '4' SET row = row + 1 WHERE row >= 2"
Error("19", "Unable to fetch row", "UNIQUE constraint failed: 4.row")
The problem's origin WHERE row >= 2" part. How to overcome this problem?
The problem's origin WHERE row >= 2" part.
I'm inclined to disagree. The problem is not with which rows are updated, it is with the order in which they are updated.
Very likely SQLite will process rows in rowid order, which almost certainly is also increasing order of the row column, since that column is an auto-incremented PK. Suppose, then, that the table contains two rows with row values 2 and 3. If it processes the first row first, then it attempts to set that row's row value to 3, but that produces a constraint violation because that column is subject to a uniqueness constraint, and there is already a row with value 3 in that column.
How to overcome this problem?
Do not modify PK values, and especially do not modify the values of surrogate PKs, which substantially all auto-increment keys are.
Alternatively, update the rows into a temporary table, clear the original table, and copy the updated values back into it. This can be extremely messy if you have any FKs referencing this PK, however, so go back to the "Do not modify PK values" advice that I led off with.
First: '4' is not a table name. The UPDATE statement expects a table name where you have written '4'. For example:
UPDATE table1 SET row = row + 1 WHERE row >= 2
Second: Just do not use row as a primary key (or unique key, for that matter) when it obviously is not meant as primary key but as a changing row number. Create a separate column that can be used as primary index of that table instead.

SQLite 3 prevent rows where all values are duplicates

I'm wondering how I can go about creating a table that won't allow rows to be inserted that are COMPLETE duplicates. By complete I mean every value has to be the same.
I'm okay with inserting rows that are identical other than 1 column's value, but not if they are all the same.
I know you can use INSERT OR IGNORE to avoid inserting duplicate rows, but the problem is that my table uses an auto incremented integer for its primary key, and INSERT OR IGNORE will still allow duplicate rows to be inserted as it sees the auto incremented id as different
Ex.
Running
INSERT OR IGNORE INTO table VALUES ("A", "B" "C");
twice will give me the following table:
id | Column A | Column B | Column C
1. "A" "B" "C"
2. "A" "B" "C"
Is there any way around this other than manually searching rows (ignoring id) for duplicates?
INSERT OR IGNORE will check any constraint, so just add one on the fields you want to check:
CREATE TABLE MyTable(
ColumnA INTEGER PRIMARY KEY,
ColumnB WHATEVER,
ColumnC,
UNIQUE (ColumnA, ColumnB, ColumnC)
);

coding many to many relationship in c++ sqlite3

I trying to code a many to many relationship in c++ sqlite3.
in the diagram below,
managers can add many job opportunities.
jobs opportunities is being add by many managers
my create table statements
"CREATE TABLE Manager(" \
"manager_id INTEGER PRIMARY KEY NOT NULL,"\
"name varchar(45) NOT NULL);"
"CREATE TABLE jobs ("
"jobId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"\
"jobTitle varchar(45) NOT NULL);"
"CREATE TABLE Add ("
"manager_id,jobId INTEGER PRIMARY KEY NOT NULL,"\
"date varchar(45) NOT NULL,"\
"FOREIGN KEY(manager_id) REFERENCES Manager(manager_id),"\
"FOREIGN KEY(job_id) REFERENCES jobs(job_id));";
my manager table is populated with the following information
1|john
2|bob
let's say manager john has added two jobs,jobTitle jobA and jobB
then my insert statement code will look like this.http://pastebin.com/0E8CzPgX
then my jobs tables is populated with the following information
1|jobA
2|jobB
the final step is to take the id of john(manager id = 1) and the two jobsId(1,2) and add it inside
the add table. I don't have an idea of how should I code
so that the add table will become like this.
add table
manager_id|job_id|date
1 | 1 |30-01-2014
1 | 2 |30-01-2014
please advise.thanks
Do you mean something like
sql = "INSERT INTO Add(manager_id,jobId,date) VALUES (?,?,?);";
?
Your problem seems to be that you defined jobID to be the primary key of the table Add, which you don't need.
jobId INTEGER PRIMARY KEY NOT NUL
A common approach to many-to-many relations in a database is to include an intermediate table.
This intermediate table (let's call it Manager_jobs) would have at least 2 columns, both referring to other tables via foreign key. The first attribute would be the primary key of Manager, the second one the primary key of jobs.
Each time you add a job, you just add an entry to Manager_jobs with the foreign keys respectively.
So, Manager_jobs would look like this:
ManagerID | JobID
==========|======
4 | 2
3 | 2
4 | 1
As you can see, Manager_jobs can encode that a Manager has multiple jobs assigned and vice versa.
This approach, of course, requires you to have some form of primary key for both data tables.

Remove rows from SQL DB that appear in a Array

I Develop with MFC Visual C++ and Oracle SQL Server.
I have SQL table with: IDs, value and time, when the application insert a new row: some ID, some Value and time being inserted.
My goal is to delete rows of values that were changed between certain time. since the data that was inserted during that time has incorrect value.
Where is the catch ? I dont need to delete all the rows that were updated in that time period, only the rows with IDs that appear on a certain CArray.
I can go through each ID from CArray and execute a delete query to that certain ID in that time period (whether there is entry or not) - problem since i can have 150K IDs to iterate
on..
Thanks
DELETE FROM table-name WHERE id in (...)
transform your array into a tempTable with one column and then delete from your destiantion table where ID in (select Id from temptable)
Here is an example:
declare #RegionID varchar(50)
SET #RegionID = '853,834,16,467,841'
declare #S varchar(20)
if LEN(#RegionID) > 0 SET #RegionID = #RegionID + ','
CREATE TABLE #ARRAY(region_ID VARCHAR(20))
WHILE LEN(#RegionID) > 0 BEGIN
SELECT #S = LTRIM(SUBSTRING(#RegionID, 1, CHARINDEX(',', #RegionID) - 1))
INSERT INTO #ARRAY (region_ID) VALUES (#S)
SELECT #RegionID = SUBSTRING(#RegionID, CHARINDEX(',', #RegionID) + 1, LEN(#RegionID))
END
delete from from your_table
where regionID IN (select region_ID from #ARRAY)