I´m using Postgres and java to write files out of a .csv into a db. In my CREATE TABLE stmnts, I have a table which stores two keys. These I want to insert. I now have a subquery but i always get a null value for the ckey, so the syntax must be wrong. The INSERT does not work. ERROR: null value in column "ckey" of relation "gamesin" violates not-null constraint. The other value I get out of a list I created. I´m using a prepared statement. Help appreciated!
CREATE TABLE Games(
Year INT PRIMARY KEY,
Name VARCHAR(32) NOT NULL,
StartDate Date NOT NULL,
EndDate Date NOT NULL
);
CREATE TABLE Cities(
CKey SERIAL PRIMARY KEY,
Name VARCHAR(128) UNIQUE NOT NULL,
Noc CHAR(3) REFERENCES Countries NOT NULL
);
CREATE TABLE GamesIn(
Year INT REFERENCES Games,
CKey INT REFERENCES Cities,
PRIMARY KEY(Year, CKey)
);
String sql = "INSERT INTO gamesin (year, ckey) VALUES (?, (SELECT ckey from cities WHERE cities.name = '\" + name + \"'))";
Related
I am trying to find a way to have duplicate value for key 1 to store in multiple genre for movieID.
I already tried auto increment on the table but still had those errors
CREATE TABLE movie_genres (
movieID INT NOT NULL AUTO_INCREMENT,
genre VARCHAR(50) NOT NULL,
PRIMARY KEY (movieID),
FOREIGN KEY (movieID) REFERENCES movies(ID)
);
ERROR 1062: 1062: Duplicate entry '1' for key 'movieID'
SQL Statement:
INSERT INTO movie.movie_genres (movieID, genre) VALUES ('1', 'Animation')
ERROR 1062: 1062: Duplicate entry '1' for key 'movieID'
SQL Statement:
INSERT INTO movie.movie_genres (movieID, genre) VALUES ('1', 'Children')
ERROR 1062: 1062: Duplicate entry '1' for key 'movieID'
SQL Statement:
INSERT INTO movie.movie_genres (movieID, genre) VALUES ('1', 'Comedy')
ERROR 1062: 1062: Duplicate entry '1' for key 'movieID'
SQL Statement:
INSERT INTO movie.movie_genres (movieID, genre) VALUES ('1', 'Fantasy')
Your database design has some fundamental problems, in particular it is missing a junction table which relates movies to their genres (1 to n). Here is one proposal for what your schema might be:
CREATE TABLE movies (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255)
);
CREATE TABLE genres (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
genre VARCHAR(255)
);
CREATE TABLE movie_genres (
movieID INT NOT NULL,
genreID INT NOT NULL,
PRIMARY KEY (movieID, genreID)
);
Now with this schema in place, here is what your inserts might look like:
INSERT INTO movies (ID, title) VALUES (1, 'Avatar');
INSERT INTO genres (ID, genre)
VALUES
(1, 'Animation'), (2, 'Children'), (3, 'Comedy'), (4, 'Fantasy');
INSERT INTO movie_genres (movieID, genreID)
VALUES
(1, 1), (1, 2), (1, 3), (1, 4);
The basic idea here is that the movies and genres tables exist only to keep track of...movies and genres. They don't "know" anything about each other. To handle the relationships between movies and genres, your updated movie_genres table comes into play. It stores only the IDs from the movies and their corresponding genres.
This is how my schema looks like:
CREATE TABLE movies (
id INT NOT NULL,
title VARCHAR(180) NOT NULL,
imdbID VARCHAR(30),
spanishTitle VARCHAR(180),
imdbPictureURL VARCHAR(2200),
year VARCHAR(5),
rtID VARCHAR(150),
rtAllCriticsRating INT,
rtAllCriticsNumReviews INT,
rtAllCriticsNumFresh INT,
rtAllCriticsNumRotten INT,
rtAllCriticsScore INT,
PRIMARY KEY (id)
);
CREATE TABLE movie_genres (
movieID INT NOT NULL AUTO_INCREMENT,
genre VARCHAR(50) NOT NULL,
PRIMARY KEY (movieID),
FOREIGN KEY (movieID) REFERENCES movies(ID)
);
I am working in a project of employees Attendance in Java (using NetBeans), I have created two tables, one for employee's data and the other to check the attendance.
Now I want to link the primary key of the first table to the second table but I do not know how. For example if you want to check the attendance it will show you the ID of the employee and when (time in / time out).
What I have tried:
This is the first table:
create table employee (
empID int primary key auto_increment,
fName varchar(100),
civilId int,
mobile int
);
The second table:
create table employeeAttendance (
id int primary key auto_increment,
empID int not null,
timeIn time,
timeOut time,
daay date,
constraint emp_fk foreign key (empID) references employee (empID)
);
and in Java I did that but could not complete it :
String sql="insert into employeeAttendance(empID,timeIn,daay)values(?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,.getText());
pstmt.setString(2,timeLabel.getText());
pstmt.setString(3,dateLabel.getText());
You did almost everything right in terms of functionality.
Please don't use text fields for integer and date if you can avoid it. Every major UI Framework has fields for this special types, so use them!
However, you should use the correct setter method of PreparedStatement. If your column is an int you should use ps.setInt, if you have a time/timestamp/date column you should use ps.setDate.
So your Java code would look like this
SimpleDateFormatter sdf = new SimpleDateFormatter("dd.MM.yyyy");
java.util.Date jtimeIn = sdf.parse(timeLabel.getText());
java.sql.Date stimeOut = new java.sql.Date(jdate.getTime()); //This part is important, jdbc uses java.sql.Dates!
java.util.Date jdaay = sdf.parse(dateLabel.getText());
java.sql.Date sdaay = new java.sql.Date(jdaay.getTime()); //This part is important, jdbc uses java.sql.Dates!
String sql="insert into employeeAttendance(empID,timeIn,daay)values(?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,Integer.parseInt(empIDAsText));
pstmt.setDate(2,stimeOut);
pstmt.setString(3,sdaay);
I've got tables Artist, Concert, and Artist_Concert, which contains many-to many connections between Artist and Concert.
The problem is: after adding a Concert with few Artists, when trying to delete rows from Artist_Concert, it only deletes only one row and nothing happens when trying to delete any others.
This is how I'm trying to delete rows in Java:
stat = connect.createStatement();
res = stat.executeQuery ("SELECT idConcert FROM concerthall.concert where ConcertName = '"+conc+"';");
res.first();
int idconc = res.getInt(1);
stat.execute ("DELETE FROM concerthall.artist_concert WHERE idConc="+idconc+"");
Artist
CREATE TABLE IF NOT EXISTS `concerthall`.`Artist` (
`idArtist` INT NOT NULL AUTO_INCREMENT,
`ArtName` VARCHAR(45) NOT NULL,
`ArtFee` INT NULL,
PRIMARY KEY (`idArtist`))
ENGINE = InnoDB
Artist-Concert
CREATE TABLE IF NOT EXISTS `concerthall`.`Artist_Concert` (
`idCA` INT NOT NULL AUTO_INCREMENT,
`idArt` INT NOT NULL,
`IdConc` INT NOT NULL,
INDEX `idart_idx` (`idArt` ASC),
INDEX `idconc_idx` (`IdConc` ASC),
PRIMARY KEY (`idCA`),
CONSTRAINT `idart2`
FOREIGN KEY (`idArt`)
REFERENCES `concerthall`.`Artist` (`idArtist`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idconct4`
FOREIGN KEY (`IdConc`)
REFERENCES `concerthall`.`Concert` (`idConcert`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
Concert
CREATE TABLE IF NOT EXISTS `concerthall`.`Concert` (
`idConcert` INT NOT NULL AUTO_INCREMENT,
`ConcertName` VARCHAR(45) NOT NULL,
`ConcertDateTime` DATETIME NOT NULL,
`Organizator` INT NOT NULL,
PRIMARY KEY (`idConcert`),
INDEX `concertorg_idx` (`Organizator` ASC),
CONSTRAINT `concertorg`
FOREIGN KEY (`Organizator`)
REFERENCES `concerthall`.`Organizator` (`idOrganizator`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
The easiest way to drop duplicates is:
ALTER IGNORE TABLE table ADD UNIQUE INDEX( a, b );
In the INDEX() part, enter the name(s) of the column(s) you only want unique entries for. I think you want:
ALTER IGNORE TABLE concerthall.artist_concert ADD UNIQUE INDEX( idConc );
Then drop the index.
My javaFx application has many tables with editable table cells to populate data from sql database.I also want to make changes in database after data editing through table cells.According to this toturial "https://docs.oracle.com/javafx/2/ui_controls/table-view.htm"
I have created my editable table cell with the following code.
item_price_col.setCellValueFactory(
new PropertyValueFactory("price")
);
item_price_col.setCellFactory(TextFieldTableCell.forTableColumn());
item_price_col.setOnEditCommit(
new EventHandler<CellEditEvent<Item, String>>() {
#Override
public void handle(CellEditEvent<Item,String> t) {
String old_price=t.getOldValue();
((Item) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setPrice(t.getNewValue());
String new_price=t.getNewValue();
System.out.println("Old Price:"+old_price);
System.out.println("New Price:"+new_price);
}
}
);
But it doesn't make any changes in database after editing.So,I think have to write update Query inside of that handle method.But I can only know old value and new value. I can't make query statement like that "update item set price=new_price where price=old_price".If I update a single price of a item to new value,every items in my item table that have the same price with my edited item will make changes to new price value.Are there any ways to solve this problem?
Here is my item table structure.
item | CREATE TABLE `item` (
`code` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`price` varchar(50) NOT NULL,
`whole_sale_price` varchar(50) NOT NULL,
`orginal_price` varchar(50) DEFAULT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
Keep an id field to your item as it is given in the database.
If you have not primary or unique key in the database probably you made some architectural mistake. Anyway there is a row id specified in some database servers.
private int id; // id field for item object.
While updating include id as condition.
update sometable set price = item.getPrice() where id = item.getId();
I know sql is not well written but I hope you'll get it
And you don't have to show value of id field in your table grid.
This technique is used in most systems
EDITED 2015.12.18
You have code column in the table. Retrieve by jdbc into your item object's id field.
There is an example
http://www.tutorialspoint.com/jdbc/jdbc-update-records.htm
My database had a lot of parent and child tables.The tables contains the foreign key which has the link with the parent table.I wants to get the information of parent table of the child table using java?How can I achieve that?
For ex,consider the student and mark table,
The student table contains the information like studentID,name.
studentID-Primary key
The marks table contains the markId,studentId,Sub1,sub2,sub3 etc
markId-Primarykey
studentID-Foreignkey refers Student table
My table creation queries are,
CREATE TABLE `Student12` (
`studentId` SMALLINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`studentId`)
)
ENGINE = InnoDB;
CREATE TABLE `Marks` (
`markId` SMALLINT NOT NULL AUTO_INCREMENT,
`subject1` SMALLINT NOT NULL,
`subject2` SMALLINT NOT NULL,
`studentId` SMALLINT NOT NULL,
PRIMARY KEY (`markId`),
CONSTRAINT `FK_Marks_Student` FOREIGN KEY `FK_Marks_Student` (`studentId`)
REFERENCES `Student12` (`studentId`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
If I give the mark table name as input, how can I get its parent or super table name student and information about student table?Any help should be appreciable.
It totally depends on the way tables are created. Foreign keys are not mandatory to create, they could be a simple column in one table with no explicit relationship to the other table. If you are very sure that the links are created explicitly (the foreign keys are defined) then you could use information_schema. But if there is no foreign key defined (which is true in most of the databases I have seen), then there is no way for you to find the links inside the database. You have to look into the code (if there is any available) and try to find a clue.
The JDBC DatasetMetaData interface provides a couple of methods that may help. (The following text is copied from the javadoc.
ResultSet getExportedKeys(String catalog, String schema, String table)
Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
Of course, these can only work if the relevant columns have been declared as foreign keys in the SQL table DDL.
You can use the DatabaseMetaData to retrieve informations about foreign keyes
and the referenced Tables. Im not sure if it works with all kinds of MySql Tables.
The principle is to use the follwing code (not tested) to retrieve information about the super tables
ResultSet rs = null;
DatabaseMetaData dm = conn.getMetaData( );
// get super tables of table marks
ResultSet rs = dm.getSuperTables( null , null, "marks" );
while( rs.next( ) ) {
System.out.println(String.format("Table Catalog %s", rs.getString("TABLE_CAT") );
System.out.println(String.format("Table Schema %s", rs.getString("TABLE_SCHEM") );
System.out.println(String.format("Table Name %s", rs.getString("TABLE_NAME") );
System.out.println(String.format("Table Name %s", rs.getString("SUPERTABLE_NAME") );
}
You can use thes informations to get additional informations about the referenced table
and the foreigen and referenced primary keys:
ResultSet rs = dm.getCrossReference( null , null , "student" , null , null , "marks" );
System.out.println(String.format("Exported Keys Info Table %s.", "marks"));
while( rs.next( ) ) {
String pkey = rs.getString("PKCOLUMN_NAME");
String ptab = rs.getString("PKTABLE_NAME");
String fkey = rs.getString("FKCOLUMN_NAME");
String ftab = rs.getString("FKTABLE_NAME");
System.out.println("primary key table = " + ptab);
System.out.println("primary key = " + pkey);
System.out.println("foreign key table = " + ftab);
System.out.println("foreign key = " + fkey);
}
And finally you can retrieve the information about the super table by
ResultSet rs = dm.getTables(null,null,"student" ,null);
System.out.println("Table name:");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
System.out.println(table);
}