PhoneGap sql checking for duplicates - sql

I want to input a query to check the database for duplicate when inserting data into the database so it would prevent the activity Name from being entered more than once in a database
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
tx.executeSql(query,[]);
}``

Create the table with name being unique:
CREATE TABLE IF NOT EXISTS dataEntryTb (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
activityName TEXT NOT NULL UNIQUE,
location TEXT NOT NULL,
time NOT NULL, date NOT NULL,
reporter NOT NULL
);
Then the database will return an error if the name is already in the table.

Related

How Do I create an autoincrement field in SQL and refer back?

I am creating a flask backend that saves details of a DND style character on an SQL server. This is the application script for the input of the character details.
#app.route("/add_char", methods=["GET", "POST"])
#login_required
def add_char():
if request.method == "POST":
cha_id = db.execute("""INSERT INTO
character_basics (
char_id, user_id, name, race, cha_class, level, experience, alignment_lc, alignment_ge,
height, weight, handedness, eye_colour, hair_colour, sex, age, status,
max_hp, current_hp, strength, dexterity, constitution, intelligence,
wisdom, charisma, fortune
) VALUES (
:char_id, :user_id, :name, :race, :cha_class, :level, :experience, :alignment_lc, :alignment_ge,
:height, :weight, :handedness, :eye_colour, :hair_colour, :sex, :age, :status,
:max_hp, :current_hp, :strength, :dexterity, :constitution, :intelligence,
:wisdom, :charisma, :fortune
)
""",
user_id = session["user_id"],
name = request.form.get("name"),
race = request.form.get("race"),
cha_class = request.form.get("cha_class"),
level = request.form.get("level"),
experience = request.form.get("experience"),
alignment_lc = request.form.get("alignment_lc"),
alignment_ge = request.form.get("alignment_ge"),
height = request.form.get("height"),
weight = request.form.get("weight"),
handedness = request.form.get("handedness"),
eye_colour = request.form.get("eye_colour"),
hair_colour = request.form.get("hair_colour"),
sex = request.form.get("sex"),
age = request.form.get("age"),
status = request.form.get("status"),
max_hp = request.form.get("max_hp"),
current_hp = request.form.get("current_hp"),
strength = request.form.get("strength"),
dexterity = request.form.get("dexterity"),
constitution = request.form.get("constitution"),
intelligence = request.form.get("intelligence"),
wisdom = request.form.get("wisdom"),
charisma = request.form.get("charisma"),
fortune = request.form.get("fortune")
)
db.execute("""INSERT into
char_academic (
cha_id, anatomy, anatomy_basic, animal_lore, animal_lore_spec,
appraisal, appraisal_spec, arcana, arcana_spec, botany_forestry,
botany_spec, engineering, engineering_spec, history, history_spec,
mathematics, mathematics_spec, religion, religion_spec
) VALUES (
:cha_id, :anatomy, :anatomy_spec, :animal_lore, :animal_lore_spec,
:appraisal, :appraisal_spec, :arcana, :arcana_spec, :botany_foresty,
:botany_spec, :engineering, :engineering_spec, :history, :history_spec,
:mathematics, :mathematics_spec, :religion, :religion_spec
)
""",
anatomy = request.form.get("anatomy"),
anatomy_spec = request.form.get("anatomy_spec"),
animal_lore = request.form.get("animal_lore"),
animal_lore_spec = request.form.get("animal_lore_spec"),
appraisal = request.form.get("appraisal"),
appraisal_spec = request.form.get("appraisal_spec"),
arcana = request.form.get("arcana"),
arcana_spec = request.form.get("arcana_spec"),
botany_forestry = request.form.get("botany_forestry"),
botany_spec = request.form.get("botany_spec"),
engineering = request.form.get("engineering"),
engineering_spec = request.form.get("engineering_spec"),
history = request.form.get("history"),
histroy_spec = request.form.get("history_spec"),
mathematics = request.form.get("mathematics"),
mathematics_spec = request.form.get("mathematics_spec"),
religion = request.form.get("religion"),
religion_spec = request.form.get("religion_spec")
)
db.execute("""INSERT into
char_profession (
char_id, agriculture, agriculture_spec, blacksmithing,
blacksmithing_spec, commerce, commerce_spec, jeweller,
jeweller_spec, leather_working, leather_spec, masonry,
masonry_spec, metal_working, metal_working_spec, sailing,
sailing_spec, tailoring, tailoring_spec, woodworking,
woodworking_spec
) VALUES (
:char_id, :agriculture, :agriculture_spec, :blacksmithing,
:blacksmithing_spec, :commerce, :commerce_spec, :jeweller,
:jeweller_spec, :leather_working, :leather_spec, :masonry,
:masonry_spec, :metal_working, :metal_working_spec, :sailing,
:sailing_spec, :tailoring, :tailoring_spec, :woodworking,
:woodworking_spec
)
""",
agriculture = request.form.get("agriculture"),
agriculture_spec = request.form.get("agriculture_spec"),
blacksmithing = request.form.get("blacksmithing"),
blacksmithing_spec = request.form.get("blacksmithing_spec"),
commerce = request.form.get("commerce"),
commerce_spec = request.form.get("commerce_spec"),
jeweller = request.form.get("jeweller"),
jeweller_spec = request.form.get("jeweller_spec"),
leather_working = request.form.get("leather_working"),
leather_spec = request.form.get("leather_spec"),
masonry = request.form.get("masonry"),
masonry_spec = request.form.get("masonry_spec"),
metal_working = request.form.get("metal_working"),
metal_working_spec = request.form.get("metal_working_spec"),
sailing = request.form.get("sailing"),
sailing_spec = request.form.get("sailing_spec"),
tailoring = request.form.get("tailoring"),
tailoring_spec = request.form.get("tailoring_spec"),
woodworking = request.form.get("woodworking"),
woodworking_spec = request.form.get("woodworking_spec")
)
db.execute("""INSERT into
cha_gen_skills (
cha_id, acrobatics, acrobatics_spec, culture, culture_spec,
dancing, dancing_spec, first_aid, first_aid_spec,
manual_labour, labour_spec, musical_ability, music_spec,
observation, observation_spec, sleight, sleight_spec,
sneak, sneak_spec, social_interaction, social_spec, tracking,
tracking_spec, upkeep_maintenance, upkeep_spec
) VALUES (
:cha_id, :acrobatics, :acrobatics_spec, :culture, :culture_spec,
:dancing, :dancing_spec, :first_aid, :first_aid_spec,
:manual_labour, :labour_spec, :musical_ability, :music_spec,
:observation, :observation_spec, :sleight, :sleight_spec,
:sneak, :sneak_spec, :social_interaction, :social_spec, :tracking,
:tracking_spec, :upkeep_maintenance, :upkeep_spec
)
""",
acrobatics = request.form.get("acrobatics"),
acrobatics_spec = request.form.get("acrobatics_spec"),
culture = request.form.get("culture"),
culture_spec = request.form.get("culture_spec"),
dancing = request.form.get("dancing"),
dancing_spec = request.form.get("dancing_spec"),
first_aid = request.form.get("first_aid"),
first_aid_spec = request.form.get("first_aid_spec"),
manual_labour = request.form.get("manual_labour"),
labour_spec = request.form.get("labour_spec"),
musical_ability = request.form.get("musical_ability"),
muscic_spec = request.form.get("music_spec"),
observation = request.form.get("observation"),
observation_spec = request.form.get("observation_spec"),
sleight = request.form.get("sleight"),
sleight_spec = request.form.get("sleight_spec"),
sneak = request.form.get("sneak"),
sneak_spec = request.form.get("sneak_spec"),
social_interaction = request.form.get("social_interaction"),
social_spec = request.form.get("social_spec"),
tracking = request.form.get("tracking"),
tracking_spec = request.form.get("tracking_spec"),
upkeep_maintenance = request.form.get("upkeep_maintenance"),
upkeep = request.form.get("upkeep_spec")
)
db.execute("""INSERT into
cha_lang_skills (
cha_id, common, common_spec, dwarven, dwarven_spec, elvish,
elvish_spec, gnomeish, gnomeish_spec, halfling, halfling_spec
) VALUES (
:cha_id, :common, :common_spec, :dwarven, :dwarven_spec, :elvish,
:elvish_spec, :gnomeish, :gnomeish_spec, :halfling, :halfling_spec
)
""",
common = request.form.get("common"),
common_spec = request.form.get("common_spec"),
dwarven = request.form.get("dwarven"),
dwarven_spec = request.form.get("dwarven_spec"),
elvish = request.form.get("elvish"),
elvish_spec = request.form.get("elvish_spec"),
gnomeish = request.form.get("gnomeish"),
gnomeish_spec = request.form.get("gnomeish_spec"),
halfling = request.form.get("halfling_spec")
)
As far as I Understand it, the first section of code creates the cha_id but then how do I call it back for the subsequent calls?
These are the SQL tables...
-- Table structure for character_basics
----
CREATE TABLE 'character_basics' ('char_id' integer PRIMARY KEY AUTOINCREMENT NOT NULL, 'user_id' integer NOT NULL, 'name' text NOT NULL, 'race' text NOT NULL, 'cha_class' text NOT NULL, 'level' integer NOT NULL, 'experience' integer NOT NULL, 'alignment_lc' text NOT NULL, 'alignment_ge' text NOT NULL, 'height' integer NOT NULL, 'weight' integer NOT NULL, 'handedness' text NOT NULL, 'eye_colour' text NOT NULL, 'hair_colour' text NOT NULL, 'sex' text NOT NULL, 'age' integer NOT NULL, 'status' text NOT NULL, 'max_hp' integer NOT NULL, 'current_hp' integer NOT NULL, 'strength' integer NOT NULL, 'dexterity' integer NOT NULL, 'constitution' integer NOT NULL, 'intelligence' integer NOT NULL, 'wisdom' integer NOT NULL, 'charisma' integer NOT NULL, 'fortune' INTEGER NOT NULL );
----
-- Table structure for char_profession
----
CREATE TABLE 'char_profession' ('char_id' integer PRIMARY KEY NOT NULL, 'agriculture' integer NOT NULL, 'agriculture_spec' text, 'blacksmithing' integer NOT NULL, 'blacksmithing_spec' text, 'commerce' integer NOT NULL, 'commerce_spec' text, 'jeweller' integer NOT NULL, 'jeweller_spec' text, 'leather_working' integer NOT NULL, 'leather_spec' text, 'masonry' integer NOT NULL, 'masonry_spec' text, 'metal_working' integer NOT NULL, 'metal_working_spec' text, 'sailing' integer NOT NULL, 'sailing_spec' text, 'tailoring' integer NOT NULL, 'tailoring_spec' text, 'woodworking' INTEGER NOT NULL , 'woodworking_spec' text);
----
-- Table structure for cha_gen_skills
----
CREATE TABLE 'cha_gen_skills' ('char_id' integer NOT NULL, 'acrobatics' integer NOT NULL, 'acrobatics_spec' text, 'culture' integer NOT NULL, 'culture_spec' text, 'dancing' integer NOT NULL, 'dancing_spec' text, 'first_aid' integer NOT NULL, 'first_aid_spec' text, 'manual_labour' integer NOT NULL, 'labour_spec' text, 'musical_ability' integer NOT NULL, 'music_spec' text, 'observation' integer NOT NULL, 'observation_spec' text, 'sleight' integer NOT NULL, 'sleight_spec' text, 'sneak' integer NOT NULL, 'sneak_spec' text, 'social_interaction' integer NOT NULL, 'social_spec' text, 'tracking' integer NOT NULL, 'tracking_spec' text, 'upkeep_maintenance' integer NOT NULL, 'upkeep_spec' text);
----
-- Table structure for char_academic
----
CREATE TABLE 'char_academic' ('char_id' integer PRIMARY KEY NOT NULL, 'anatomy' integer NOT NULL, 'anatomy_spec' text, 'animal_lore' integer NOT NULL, 'animal_lore_spec' text, 'arcana' integer NOT NULL, 'arcana_spec' text, 'botany_forestry' integer NOT NULL, 'botany_spec' text, 'engineering' integer NOT NULL, 'engineering_spec' text, 'history' integer NOT NULL, 'history_spec' text, 'appraisal' INTEGER NOT NULL , 'appraisal_spec' text, 'mathematics' INTEGER NOT NULL , 'mathematic_spec' text, 'religion' INTEGER NOT NULL , 'religion_spec' text);
Thanks
Ed

Cannot resolve logical: syntax error for sql

Not sure how to correct this logical syntax error, help would be appreciated!
Traceback (most recent call last):
File "c:\Users\M\Desktop\Coding\Course4wk4sql.py", line 7, in
cur.executescript('''
sqlite3.OperationalError: near "#logical": syntax error
PS C:\Users\M\Desktop\Coding> sqlite3.OperationalError: near "#logical": syntax error
Here is the code:
import json
import sqlite3
conn = sqlite3.connect ('rosterdb.sqlite')
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE #logical key
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id) #Going to force combination of these two to be unique
)
''')
filename = "roster_data.json"
jsondata = open(filename)
data = json.load(jsondata)
for entry in data:
user = entry[0]
course = entry[1]
instructor = entry[2]
user_statement = """INSERT OR IGNORE INTO User(name) VALUE 9 ? )"""
SQLparams = (user, )
cur.execue(course_statement, SQLparams)
course_statement = """INSERT OR IGNORE INTO Course(title) VALUES ( ? )"""
sqlparams = (course, )
cur.execute(course_statement, SQLparams)
courseID_statement = """SELECT id FROM Course WHERE title = ?"""
SQLparams = (course, )
cur.execute(courseID_statement. SQLparams)
courseID =cur.fetone()[0]
userID_statement = """SELECT id FROM User WHERE name = ?"""
SQLparams = (user, )
cur.execute(userID_statement, SQLparams)
userID = cur.fetchone()[0]
member_statement = """INSERT INTO Member(user_id, course_id, role)
VALUES(?, ?, ?)"""
SQLparams = (userID, courseID, instructor)
cur.execute(member_statement, SQLparams)
conn.commit()
test_statement = """
SELECT hex(User.name || Course.title || Member.role ) AS X FROM
User JOIN Member JOIN Course
ON User.id = Member.user_id AND Member.course_id = Course.id
ORDER BY X
"""
cur.execute(test_statement)
result = cur.fetchone()
print("RESULT: " + str(result))
#Closing the connection
cur.close()
conn.close()
You are using non-sql style comments eg #logical key in the sql script. While # is used for commenting in python -- or /* multi line comment */ is typically used in sqlite comments.
As a result you are getting a syntax error. You may remove these python style comments or attempt to replace them with sqlite style comments

How to get an error message in R when trying to enter a duplicated key in a MySQL table?

Take a SQL table defined by:
CREATE TABLE `raw_dummy_code` (
`code` int DEFAULT NULL,
`description` text COLLATE utf8_unicode_ci,
`datestart` date DEFAULT NULL,
`dateend` date DEFAULT NULL,
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
and a R data frame defined by:
raw_dummy_code <- data.frame(code = c(4, 4L, 4L),
datestart = c("2001-01-01", "2002-01-01", "2002-01-01"),
dateend = c("2001-12-31", "2500-01-01", "2500-01-01"),
description = c("old","recent","recent"),
stringsAsFactors = FALSE)
When I try to insert the data frame in the database :
con <- RMySQL::dbConnect(RMySQL::MySQL(), dbname = "test")
RMySQL::dbWriteTable(con, "raw_dummy_code", raw_dummy_code, row.names = FALSE, append = TRUE)
RMySQL::dbDisconnect(con)
RMySQL::dbWriteTable inserts only one row in the database. This is normal, since there are duplicated rows, but the problem is that there is no error message returned.
How to get the error message from MySQL when trying to enter a duplicated key?

JPA/Hibernate not using all fields in composite primary key

I have a many-to-one relationship as below (I have removed columns that do not contribute to this discussion):
#Entity
#SecondaryTable(name = "RecordValue", pkJoinColumns = {
#PrimaryKeyJoinColumn(name = "RECORD_ID", referencedColumnName = "RECORD_ID") })
Class Record {
#Id
#Column(name = "RECORD_ID")
long recordId;
#OneToMany(mappedBy="key")
Set<RecordValue> values;
}
#Entity
class RecordValue {
#EmbeddedId
RecordValuePK pk;
#Column
long value;
#ManyToOne
#MapsId("recordId")
private Record key;
}
#Embeddable
class RecordValuePK {
#Column(name = "RECORD_ID")
#JoinColumn(referencedColumnName = "RECORD_ID", foreignKey = #ForeignKey(name = "FK_RECORD"))
long recordId;
#Column(name = "COLLECTION_DATE")
LocalDate collectionDate;
}
When hibernate creates tables, the RecordValue table has primary key consisting of only RECORD_ID and NOT COLLECTION_DATE.
What could be the problem?
Hibernate debug log shows the following:
DEBUG - Forcing column [collection_date] to be non-null as it is part of the primary key for table [recordvalue]
DEBUG - Forcing column [key_record_id] to be non-null as it is part of the primary key for table [recordvalue]
DEBUG - Forcing column [record_id] to be non-null as it is part of the primary key for table [recordvalue]
.
.
Hibernate:
create table Record (
RECORD_ID bigint not null,
primary key (RECORD_ID)
)
Hibernate:
create table RecordValue (
COLLECTION_DATE date not null,
VALUE bigint not null,
key_RECORD_ID bigint not null,
RECORD_ID bigint not null,
primary key (RECORD_ID)
)
Removing the #SecondaryTable specification has resolved this issue. The #SecondaryTable specification was forcing both tables to have the same the primary key. The found this solution after reading this blog:
https://antoniogoncalves.org/2008/05/20/primary-and-secondary-table-with-jpa.

How to sort Microsoft Azure database table data BY DATE

I am trying to sort the rows in my table by the latest date first.
var userParkingHistory = from j in dataGateway.SelectAll() select j ;
userParkingHistory = userParkingHistory.Where(ParkingHistory => ParkingHistory.username == User.Identity.Name);
return View(userParkingHistory);
I can currently display the rows sorted by the username but I also want it to sort by the latest date first.
In my gateway, this is how I select the list:
public IEnumerable<T> SelectAll()
{
return data.ToList();
}
Where and How do I sort the data according to the latest date first ?
This is how I define my table:
CREATE TABLE [dbo].[ParkingHistory] (
[parkingHistoryId] INT IDENTITY (1, 1) NOT NULL,
[carparkId] INT NULL,
[username] VARCHAR (255) NULL,
[date] DATETIME NULL,
[description] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([parkingHistoryId] ASC)
);
Linq has orderby:
var userParkingHistory = from j orderby j.date in dataGateway.SelectAll() select j ;
Alsi, List has various extension methods to sort itself.
Try this:
var userParkingHistory = dataGateway.SelectAll().Where(p => p.username == User.Identity.Name).OrderBy(p => p.date).ToList();
return View(userParkingHistory);