Disallow Duplicates when adding to SQLite Database - java

I currently have a student grade/class input program which accepts the following inputs: Student ID, First Name, Last Name, Class ID, Class Name, Grade Point, and Letter Grade.
For obvious reasons I would like to limit the user from entering Duplicate records for the same student/course (student id, class id) pair, as well as duplicate records for the same student id and first name/last name. (Two students should not be able to fill the same ID.
Currently I have a very basic method to add this data, what is the best method to implement my intentions?:
db=openOrCreateDatabase("STUDENTGRADES", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS CUSTOMER_TABLE(studentid VARCHAR, fname VARCHAR, lname VARCHAR, classid VARCHAR, classname VARCHAR, pointgrade INTEGER, lettergrade VARCHAR);");
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(fname.getText().toString().trim().length()==0||
lname.getText().toString().trim().length()==0 || studentid.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter First & Last Name and Student ID");
return;
}
db.execSQL("INSERT INTO CUSTOMER_TABLE VALUES('"+studentid.getText()+"','"+fname.getText()+"','"+lname.getText()+"','"+classid.getText()+"','"+classname.getText()+
"','"+pointgrade.getText()+"','"+lettergrade.getText()+"');");
showMessage("Success", "Student Record added successfully");
clearText();
}
});

You can use method insertWithOnConflict with CONFLICT_IGNORE flag, if you don't want to replace this rows. If there is no same raw, method returns -1, so you can handle it
EDITED:
At first, you need to create UNIQUE rows (in your case - class id and student id):
db.execSQL("CREATE TABLE YOURDB ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "STUDENTID TEXT UNIQUE, "
+ "CLASSID TEXT UNIQUE);");
then create variable for checkking result of method
int k = 0;
try to insert values and get result into our k
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
k = db.insertWithOnConflict("YOURDB",null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
db.close();
}
and, finally check your variable (I was made all in AsyncTask, so method for check is located in onPostExecute() method)
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (k==-1){
Toast.makeText(getApplicationContext(), "Same raws", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not same raws", Toast.LENGTH_SHORT).show();
}
}
if there are coincidence of values, DataBase will not be updated and your k get -1 value, so, you can make Toast or something else to handle it
EDIT 2:
about ContentValue initialize:
at first, you should get values, for example, you get them from editText:
String studentIdUpdate = studentEditText.getText().toString();
String classIdUpdate = classEditText.getText().toString();
and then create ContentValues variable and put values into it
ContentValues contentValues = new ContentValues();
contentValues.put("STUDENTID", studentIdUpdate);
contentValues.put("CLASSID", classIdUpdate);

When you use a simple flat file containing all that information, it is easy to get things out of sync. That is, same student ID associated with multiple names, or same class ID associated with multiple class names. And extra work is required to keep things in sync if a student name or class name needs to be changed. Not to mention the need to minimize duplicate records. The first step to sorting out this mess is to redesign your database. For the data you mention here, I would use three tables:
Students
ID Name
------------ ---------------------------------
1 Henry
2 Molly
3 George
Classes
ID Name
------------ --------------------------------
1 Ohio History
2 US History
3 World History
Grades
StudentID ClassID Grade LetterGrade
------------ ------------ ------------ ------------
1 1 98 A
2 3 85 B
3 2 77 C
1 2 85 B
3 3 92 A
Set the primary key on Students and Classes to the ID field, and for Grades to a composite of (StudentID, ClassID). This will prevent a given student from having multiple grades for the same class, and will also prevent multiple students from having the same id. Same for classes.
Now your user interface can let the user choose a student, choose a class, then assign a grade. The letter grade can be calculated, or keyed.
Here is how I would define the tables:
create table if not exists students (
id integer primary key autoincrement,
last_name varchar,
first_name varchar);
create table if not exists classes (
id integer primary key autoincrement,
name varchar);
create table if not exists grades (
student_id integer not null,
class_id integer not null,
point_grade integer,
letter_grade varchar,
primary key (student_id, class_id),
foreign key (student_id) references students,
foreign key (class_id) references classes)
without rowid;
The foreign key constraints prevents grades from being entered for non-existent students or classes, and also prevents students or classes with grades from being deleted. There are other clauses to allow you to delete all grades for a student or class if a student or class is deleted.
The relationship between the students and classes is called a many-to-many relationship. That means that many students can be assigned to a single class, and many classes can be assigned to a single student. Not that the only keys that are auto increment are the student and class ID's. The ID's in the grades file reference the associated student and class rows. In the above data example,
Henry has grades for two classes (Ohio History (98) and US History (85)), Molly has grades for only one class (World History (85)), and George has grades for two classes (US History (77) and World History (92)).
You can create a single view that combines the students classes and grades like this:
create view if not exists student_view (
last_name, first_name, class_name, point_grade, letter_grade)
as (
select last_name, first_name, name, point_grade, letter_grade
from students
join grades on grades.student_id = students.id
join classes on classes.id = grades.class_id;

Related

Increment variable in JSP page

I am working on a flight reservation system where users can log into an account to make reservations.
In my sql database, I have a table called ticket where there is a column called seatnum. I have another table called aircraft and that has a column called seats.
In my jsp page, I want to assign a random seat number to a person buying a ticket, but I can only assign so many seats before the seats in the aircraft table gets full.
I want to declare a global counter for the number of seats I assign to a particular flight, but my counter keeps being reset to 0 but I can't declare a static variable in a jsp. What should I do instead?
CREATE TABLE `ticket` (
`cid` int,
`flight_num` int,
`ticket_num` int NOT NULL AUTO_INCREMENT,
`seatnum` int,
PRIMARY KEY (`ticket_num`),
FOREIGN KEY (`flight_num`) REFERENCES flight (`flight_num`) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (`cid`) REFERENCES user (`cid`) ON UPDATE CASCADE ON DELETE CASCADE
)
CREATE TABLE `aircraft` (
`2letterid` varchar(2),
`aircraft_num` int,
`seats` int,
PRIMARY KEY (`2letterid`, `aircraft_num`),
FOREIGN KEY(`2letterid`) REFERENCES `airline` (`2letterid`)
)
int counter = 0;
String seats = "select seats from flight join aircraft(flight_num) " +
"where flight_num = " + flightNum;
if (counter > seats) {
enter a waiting list
}
You can store the counter in a hidden field or in the session.

How do you combine tuples with repeating attributes into one tuple?

I created a java class with the same name as a table from a SQL database, and using the retrieved information from that table I created multiple objects out of that Java class, and stored them inside An ArrayList.
CREATE TABLE `orderdetails` (
`orderNumber` int(11) NOT NULL,
`productCode` varchar(15) NOT NULL,
`quantityOrdered` int(11) NOT NULL,
`priceEach` decimal(10,2) NOT NULL,
`orderLineNumber` smallint(6) NOT NULL,
PRIMARY KEY (`orderNumber`,`productCode`),
KEY `productCode` (`productCode`),
CONSTRAINT `orderdetails_ibfk_1` FOREIGN KEY (`orderNumber`) REFERENCES `orders` (`orderNumber`),
CONSTRAINT `orderdetails_ibfk_2` FOREIGN KEY (`productCode`) REFERENCES `products` (`productCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
tuples have repeating orderNumbers, for example:
(10100,'S18_1749',30,'136.00',3),
(10100,'S18_2248',50,'55.09',2),
(10100,'S18_4409',22,'75.46',4),
Each tuple is then turned into a java object of the class with the same name as the table, and to be stored inside an Arraylist.
public ArrayList<OrderDetails> getOrders(String tableName) throws SQLException{
ArrayList<OrderDetails>od=new ArrayList<OrderDetails>();
try {
String query="SELECT * FROM "+tableName;
Statement s= con.createStatement();
ResultSet rs= s.executeQuery(query);
while(rs.next()) {
int orderNumber=rs.getInt("orderNumber");
String productCode=rs.getString("productCode");
int quantityOrdered=rs.getInt("quantityOrdered");
double priceEach=rs.getDouble("priceEach");
int orderLineNumber=rs.getInt("orderLineNumber");
OrderDetails temp=new OrderDetails(orderNumber, productCode, quantityOrdered, priceEach, orderLineNumber);
od.add(temp);
}
}
catch(SQLException e) {
System.out.println("SQL exception happened while retriving data, close connection");
throw new RuntimeException(e);
}
return od;
}
I am trying to Loop through the ArrayList and output the total amount of value (priceEach times quantityOrdered )for each checkNumber. But if I simply just loop through the ArrayList one object by object, that isn't going to work. As I will simply see the sum for each object, not each checkNumber, on the console.
ArrayList<OrderDetails>od= this.getOrders("orderdetails");
for(int i=0;i<=od.size();i++) {
System.out.println(od.get(i).getPriceEach()*od.get(i).getQuantityOrdered());
}
I'm expecting something like this to show up on console (no repeating checkNumber)
CheckNumber 10100, total value: 8494.62 (if you add up the product between priceEach and quantityOrdered for the three tuples shown above earlier in my question is the rsult)
In short is there a way for me to combine objects with repeating attributes into one?
I apologize if my question seems very vague and you don't know exactly what the problem is.
It would be greatly appreciated if you try to reach out for me and ask for further clarifications, sometimes it is very difficult to describe a problem that's too specific..
Why not simply do the computation in the database? SQL is a set-based language that is very efficient at this type of operation, compared to an iterative loop in Java.
Consider the following aggregate query:
select orderNumber, sum(quantityOrdered * priceEach) totalValue
from mytable
group by orderNumber
This gives you one record per order, with the total value over all corresponding rows.

How to make two columns auto increment in Sqlite

I'm Using OID as a primary key with auto increment, but I want to make Txn No also auto increment. Is there any way to make it auto increment? I tried to use loop, but it seems doesn't work.
When I click the "Save" one time, Next time should be Txn No "2", but I can't think of it, because I used OID to Auto increment, so Txn No can't use it.
Here is My Code:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Person.db";
public static final String TABLE_NAME = "Person_Table";
public static final String COL_1 = "OID";
public static final String COL_2 = "TxnNo";
public static final String COL_3 = "Name";
public static final String COL_4 = "Amount";
public static final String COL_5 = "Date";
public static final String COL_6 = "Description";
public static final String COL_7 = "Description2";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (OID INTEGER PRIMARY KEY AUTOINCREMENT," +
"TxnNo TEXT, Name TEXT, Amount INTEGER,Date TEXT, Description TEXT,Description2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String TxnNo, String Name, String Amount, String Date, String Description, String Description2) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, TxnNo);
contentValues.put(COL_3, Name);
contentValues.put(COL_4, Amount);
contentValues.put(COL_5, Date);
contentValues.put(COL_6, Description);
contentValues.put(COL_7, Description2);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
First thing with SQLite AUTOINCREMENT doesn't actually increment the ID, using INTEGER PRIMARY KEY will result in much the same, other than when you've had 9223372036854775807 rows added. All AUTOINCREMENT does is enforce an increasing number (so when the largest rowid is reached an SQLITE FULL exception occurs), otherwise (without AUTOINCREMENT) free lower numbers can be allocated, thus potentially circumventing the SQLITE FULL exception.
In fact what INTEGER PRIMARY KEY (with or without AUTOINCREMENT) does is make the columnn alias of the rowid (a normally hidden column that is given a unique 64 bit signed integer).
One of the rules is that only a single column can have INTEGER PRIMARY KEY (or PRIMARY KEY) coded per table. Which is the issue that you are facing.
A Solution
A way to do what you wish is to utilise a TRIGGER that is triggered when a new row is inserted and use it to update the inserted row with a value that is suffixed with the OID. e.g.
CREATE TRIGGER IF NOT EXISTS increment_tax_number
AFTER INSERT ON Person_Table
BEGIN
UPDATE Person_Table SET TxnNo = 'Txn no '||new.OID WHERE OID = new.OID;
END;
INSERT INTO Person_Table VALUES(null,'not a valid tax number as yet','Fred',15000,'2018-01-01','blah','more blah');
INSERT INTO Person_Table VALUES(null,'not a valid tax number as yet','Bert',25000,'2018-03-04','blah','more blah');
SELECT * FROM Person_Table;
For a new table the above results in :-
This solution could be incorporated by using :-
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (OID INTEGER PRIMARY KEY AUTOINCREMENT," +
"TxnNo TEXT, Name TEXT, Amount INTEGER,Date TEXT, Description TEXT,Description2 TEXT)");
db.execsql("CREATE TRIGGER If NOT EXISTS increment_tax_number AFTER INSERT ON Person_Table
BEGIN
UPDATE Person_Table SET TxnNo = 'Txn no '||new.OID WHERE OID = new.OID;
END");
}
You would need to delete the App's data, uninstall the App or increase the version number (i.e. use super(context, DATABASE_NAME, null, 2)). Noting that you would lose any existing data. To not lose data would be more complicated.
A More efficient solution
Of course, there is also the option of just utilising the OID as it appears that you want the numeric part appended to Txn No, so there is no need to even have a column that is a waste. The Txn No 1, Txn No 2 etc can be generated when required.
e.g. The following will generate the Txn No purely from the OID column :-
SELECT Name, 'Txn No '||OID AS txn_no,Amount,Description,Description2 FROM Person_Table;
Resulting in :-
To incorporate this solution you don't need to do anything other than use suitable queries (although you may wish to do away with the TxnNo column)
More about AUTOINCREMENT
Using AUTOINCREMENT incurs overheads that are rarely required. The SQLite documentation includes :-
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
disk I/O overhead and should be avoided if not strictly needed. It is
usually not needed.
SQLite Autoincrement
The overheads are because when AUTOINCREMENT is used the algorithm used to determine the new rowid adds a second stage of getting the respective row from the sqlite_sequence table and then using the higher of this and the highest rowid in the table (without AUTOINCREMENT just the highest rowid in the table is used). So the overheads are having to maintain and access this additional table for every insert.
As such it would be more efficient to define your table with either :-
CREATE TABLE IF NOT EXISTS Person_Table (OID INTEGER PRIMARY KEY,TxnNo TEXT, Name TEXT, Amount INTEGER,Date TEXT, Description TEXT,Description2 TEXT);
If you decide to have the TxnNo column
or :-
CREATE TABLE IF NOT EXISTS Person_Table (OID INTEGER PRIMARY KEY, Name TEXT, Amount INTEGER,Date TEXT, Description TEXT,Description2 TEXT);
If using the derived Txn No (more efficient solution)
You can't have 2 AUTOINCREMENT variables in the table. But now you declere: TxnNo TEXT it's very strange.
You can look for these variants sql-auto-increment-several
It may be, Sqlite not providing autoincrement for two column.
So i have several ways
first of all you need to use "TxnNo" as INTEGER or LONG.
at the time while you insert new record get Max "TxnNo" and increase it by 1. It is possible only if your whole database is synced in local. if it's not fully synced then its may occur duplication .
Use "TxnNo" as LONG and set current time in milliseconds. this will give you unique number every time. no need to get max. I would like to prefer this way. cause i'm also using this way.

SQLite Database - RESET information

I'm currently making a code that uses a database. This is the class of the database:
public class ScriptDLL {
public static String getCreateTableCliente(){
StringBuilder sql = new StringBuilder();
sql.append(" CREATE TABLE IF NOT EXISTS CLIENTE (");
sql.append(" CODIGO INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,");
sql.append(" NOME VARCHAR (250) NOT NULL DEFAULT (''),");
sql.append(" ENDERECO VARCHAR (255) NOT NULL DEFAULT (''),");
sql.append(" EMAIL VARCHAR (200) NOT NULL DEFAULT (''),");
sql.append(" TELEFONE VARCHAR (20) NOT NULL DEFAULT ('') )");
return sql.toString();
}
}
Ok, so i want to make a SQLite code to set CODIGO back to 1. How could i write this code?
Thanks!
I would suggest to increment the version by 1 and the old table is dropped and new table is created, this will avoid failure due to uniqueness constraint if records already exist in the table(you take care of migration ofcourse). If you have specific need just to reset codigo then try the below code. It resets the value to 1 in the internal sqllite record SQLITE_SEQUENCE.
Refer documentation which explains more about autoincrement and SQLITE_SEQUENCE : https://sqlite.org/autoinc.html
public static String resetKey(){
return "UPDATE SQLITE_SEQUENCE SET seq = 1 WHERE name = CLIENTE";
}
If this is just a one-off then just Delete the App's data, or uninstall the App and rerun.
If you want to do this frequently (ignoring the fact that relying upon the column being specific values most likely indicates a flaw in the design) then:-
You could DROP and recreate the table as is often done in the onUpgrade method of the Database Helper. Doing this in the onUpgrade method could be problematic/complicated if you had multiple tables and potentially even more complicated if you had multiple versions.
You could have a specific method such as :-
public void resetCODIGO() {
this.getWritableDatabase.execSQL("DROP TABLE IF EXISTS CLIENTE;");
this.getWritableDatabase.execSQL(getCreateTableCliente());
}
DROPing a table will result in the respective row in the sqlite_sequence table being deleted by SQLite.
The sqlite_sequence table has a row per table that has a column with AUTOINCREMENT (only 1 allowed per table).
the sqlite_sequence table has two defined columns name for the table name and seq for the last inserted sequence number.
Another solution that would involve DROP and CREATE BUT does involve updating the sqlite_sequence table could be to delete all rows from the table and to then delete the respective row in the sqlite_sequence table.
Thus alternately you could have :-
public void resetCODIGO() {
this.getWritableDatabase.delete("CLIENTE");
String whereclause = "name=?";
String[] whereargs = new String[]{"CLIENTE"};
this.getWritableDatabase.delete(
"sqlite_sequence",
whereclause,
whereargs
);
}
Note the above code is in-principle code and hasn't necessarily been tested, so it may contain some errors.

Online restaurant reservation system (data structures)

I have a task to design an online reservation system.
Where a user can enter zip code/ no of people/time of reservation and get a list of restaurants. Assumption (User and restaurant are always in the same city)
Each restaurant can have multiple tables with different number of seats. So, 2 tables that seat 4 people and 4 tables that seat 4 people.
I'm having trouble coming up with the right data structures to use.
My classes are as follows
Restaurant : Contains timeofopening, timeOfClosing, totalNoOfSeatsAvailable
Not sure how i will store table information within the restaurant. It doesn't make sense to have a separate class for the table. All the info i need is howManytables are free and what are their sizes.
Reservation: This maintains the actual reservation and allows to cancel reservation
ReservationSystem :
contains the interface to `List checkAvailability(long time, int people)'
How will this return this list? I initially thought of using a priorityQueue to maintain a queue with max no of seats available. But then i will go through that list to see if the time is correct to even make the reservation and then once a reservation is made,update this queue. One problem is the queue does all duplicates.
My specific questions are:
How do i store the table information within each restaurant.
What is the best way to maintain this list of restaurants so i can give return a list without having to sort this information everytime.
EDIT:
For the question on how to store the table information. My specific concern is
that storing a table class would mean that i'm creating un necessary objects. Here's my reasoning. 5 tables that seat 2 people each with have the exact same objects - i mean there isn't any meaningful information that will be differnet among them. I just need to numbers. no of seats/table.(If i have a table of 4 but 3 peole, I will consider this table taken)
I thought of creating 3 arrays. Lets say table represent 1,2 etc so int[] differentSeatingOnTable; its indexes are tables and values are seats allowed. Next an array of tables with totalNoOfThosetable where indexs are tables and values are total number of such table. Similary for free tables freeTables where index are table and how many of such free table are left.
1. ) If you just store the amount of seats in a restaurant, you're shooting yourself in the foot. Suppose I need to make a reservation for 16 people, and they all must be on the same table (yes, I need a pretty long table). Your system could take my guests to someplace where they'd have to sit in 8 tables for two people each.
You do need a table class. Then your restaurants need to have collections of tables. If you want to know how many seats you have in a restaurant, you just have to iterate through its table collection and count the seats. And if you want to know if you can sit a family in a single table in a restaurant, you just have to check whether it has any table with that amount of seats.
EDIT: there is a more minimalistic way to store seats per restaurant. Use a dictionary, hash table or any other structure that holds keys and associated values. So have the key represent a type of table. The key may be an integer saying how many people the table sits. The value is the amount of tables of that type present in the restaurant. I think this is way better than my original suggestion.
So, for example, a restaurant with such a hash table:
Key | Value
4 | 5
2 | 8
16 | 1
Has five tables with 4 seats each, 8 tables with 2 seats each, and a single long table that sits 16 people.
(Also using a table to store tables is so meta).
2. ) Your reasoning is right for the reservations. If it is doing duplicates, you should post a more especific question showing how you're doing it so we can try and help you locate the bug.
Relational databases make both these requirements easy.
You'll have two tables: RESTAURANT and SITTING (TABLE is a reserved word in SQL) with a one-to-many relationship between them.
A RESTAURANT will have a name, so you can ORDER BY name.
package model;
class Table {
private int id;
private int numSeats;
public Table(int id, int numSeats) {
this.id = id;
this.numSeats = numSeats;
}
public int getId() { return this.id; }
public int getNumSeats() { return this.getNumSeats; }
}
class Restaurant implements Comparable {
private String name;
private List<Table> tables;
public Restaurant(String name) {
this.name = name;
this.tables = new ArrayList<Table>();
}
public void addTable(Table t) { this.tables.add(t); }
public void removeTable(int id) {
for (Table t : this.tables) {
if (t.getId() == id) {
this.tables.remove(t);
break;
}
}
}
public int getCapacity() {
int capacity = 0;
for (Table t : this.tables) {
capacity += t.getNumSeats();
}
return capacity;
}
public int compareTo(Restaurant r) {
return this.name.compareTo(r.name);
}
}
1) well..i think it makes more sense if you created the table class.its easier than trying to cramp it in the restaurant class.and you would find it easier too
2)maintain a primary key field,maybe a composite key,marking out the uniques,this could keep out duplicates
Reccomendations:
Res_Table class
Restaurant class
primary key fields with ORDERING

Categories