How to use PreparedStatement with foreign key - java

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);

Related

Inserting a table with two key values

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 + \"'))";

How to automatically insert date and time into sql table

I've created a table name EventLog7 in SQL Server 2008 :
create table EventLog7(
EventId int not null identity(1,1),
EventDate datetimeconstraint DF_myDate DEFAULT (getdate()),
ObjectId varchar(50),
Name varchar(50),
Value varchar (50)
)
In NetBeans, there are three jtextfields which help to insert data into EventLog SQL Table (ObjectId, Name, Value) when I press the button.
Mentioned below action button code:
String objectid=jTextField1.getText();
String value=jTextField2.getText();
String name=jTextField3.getText();
try{
DoConnect();
st=conn.createStatement();
String sql = "insert into EventLog7 values('"+objectid+"','"+name+"','"+value+"')";
pst = conn.prepareStatement(sql);
pst.execute();
rs=st.executeQuery("select * from EventLog7");
jTable1.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
So, i want that when I insert values of ObjectId,Name,Value in three jtextfiles then Sql table will insert automatically date and time with these data.
But according to my code, it's showing error
Column names or number of supplied values does not match table definition
So please provide me right way.
String sql = "insert into EventLog7 values('"+objectid+"','"+name+"','"+value+"')";
line will be
String sql = "insert into EventLog7(ObjectId, Name, Value, EventDate) values('"+objectid+"','"+name+"','"+value+"',GETDATE())";
I do not know how the IDs is generated sql-server , you may need to set it as well if that is not auto assign/increment.
And I can say this is not secure, you need to use ?s instead of your variables and use set methods to set them as a_horse_with_no_name reminds. Use what I suggested only for mitigating the error you have now.

Insert random integer from java to mysql as unique ID

How do I insert a generated random integer from java and insert into MySQL as unique id?
generate random number
Random rand = new Random();
int x = rand.nextInt(100000);
before storing to database you have to check that number is already stored or not.
after checking that you can insert.
why do you insert random number as a unique id?.you can auto increment your primary key.then you can easily insert unique number for you primary key.and no need to create random number.
You could do it inverse: use an AUTOINCREMENT primary key on the table and per JDBC do not insert that primary key, but afterwards query the key generated by MySQL, concurrency safe.
try (PreparedStatement stm = conn.prepareStatement(
"INSERT INTO moviesTbl (title, ...) VALUES(?, ? ...)")) {
stm.setString(1, title);
stm.setString(2, ...);
...
int updateCount = stm.executeUpdate();
if (updateCount != 0) {
try (ResultSet genKeys = stm.getGeneratedKeys()) {
if (genKeys.next()) { // At most 1 record inserted
// Normally only one key generated per record.
int generatedId = genKeys.getInt(0);
...
}
} // Close result set.
}
} // Closes stm
JDBC returns a ResultSet as you could have inserted several records. And then you could have several generated keys per record.
Storing a UUID has not a full support in MySQL; maybe that the JDBC driver has support already.
A UUID is a 128 bit number, MaySQL BINARY(16), or CHAR(36) with something like this
CREATE FUNCTION `BINTOUUID`(UUID BINARY(16)) RETURNS char(36)
BEGIN
RETURN concat(HEX(LEFT(uuid,4)),'-', HEX(MID(uuid,5,2)),'-', HEX(MID(uuid,7,2)),
'-',HEX(MID(uuid,9,2)),'-',HEX(RIGHT(uuid,6)));
END
As I think you do not mean this, I leave it at that.

Getting foreign key and refering table name of particular database table from metadata DatabaseMetaData using JAVA class

I am writing java class to get all connection database objects(tables). I have used
rs = meta.getExportedKeys(conn.getCatalog(), null, "account_adjustment");
while (rs.next()) {
String fkTableName = rs.getString("FKTABLE_NAME");
String fkColumnName = rs.getString("FKCOLUMN_NAME");
int fkSequence = rs.getInt("KEY_SEQ");
}
which is giving parent table and it's column linked this asked table(account_adjustment)
and also I tried
rs1 = meta.getImportedKeys(conn.getCatalog(), null, "account_adjustment");
while (rs1.next()) {
String fkTableName = rs1.getString("FKTABLE_NAME");
String fkColumnName = rs1.getString("FKCOLUMN_NAME");
int fkSequence = rs1.getInt("KEY_SEQ");
}
which is giving current table(account_adjustment) table and it's foreign key column name
but I want table name with which this foreign key is linked
I have got solution bt in other way not using java,, instead of getting values using java i executed query to 'information_schema' (which is there by default in MySQL) database and 'REFERENTIAL_CONSTRAINTS' table to get all reference of respective tables of required database

How to get super table information in java?

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);
}

Categories