How to check database for duplicates before inserting? - java

I would like to check the database for duplicates before inserting into the database. It is only considered a duplicate when plateNo, driverID and resDate match.
Here is how I get the data that will be inserted to the database
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String client = (String) clientCmb.getSelectedItem();
String[] cparts = client.split("-");
String cpart = cparts[0];
String driver = (String) driverCmb.getSelectedItem();
String[] dparts = driver.split("-");
String dpart = dparts[0];
String van = (String) vanCmb.getSelectedItem();
java.util.Date oDate = jXDatePicker2.getDate();
DateFormat oDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = oDateFormat.format(oDate);
model2.addRow(cpart, dpart, van, date);
}
And here's the code for my addRow method
public void addRow(String client, String driver, String van, String res){
try {
String sqlRes = "Select * from reservation";
rs = st.executeQuery(sqlRes);
rs.moveToInsertRow();
rs.updateString("clientID", client);
rs.updateString("plateNo", van);
rs.updateString("driverID", driver);
rs.updateString("resDate", res);
rs.insertRow();
rs.moveToCurrentRow();
rs = st.executeQuery(sqlRes);
this.fireTableDataChanged();
} catch (SQLException ex) {
Logger.getLogger(MyModel2.class.getName()).log(Level.SEVERE, null, ex);
}

Let the database do the work for you. Define a unique index/constraint specifying that those three values are unique in the table:
create unique index unq_reservation_3 on reservation(plateNo, driverID, resDate);
If you attempt to insert a duplicate -- or do an update that results in a duplicate -- then the database will return an error. You simply need to catch the error.

Use MERGE statement: T-SQL or ORACLE, or for MySQL:
PreparedStatement p = con.prepareStatement("
INSERT INTO reservation tgt (clientID, plateNo, driverID, resDate)
SELECT (? As clientID, ? As plateNo, ? As driverID, ? As resDate)
FROM DUAL ins
LEFT JOIN reservation ref
ON ref.resDate = ins.resDate
AND (ref.plateNo = ins.plateNo OR ref.driverID = ins.driverID)
WHERE ref.clientID IS NULL;
");
p.setString(1, client);
p.setString(2, van);
p.setString(3, driver);
p.setString(4, res);
return p.executeUpdate(); /* 1 - Success | 0 - Ignored Duplicate */

Related

How to get the unique columns from a given table?

Lets say I have a table called "person" and it has 4 columns (name, last_name, city, pincode). Two of those columns (name, last_name) are unique columns. I want to get these two columns from the JDBC driver. How can I get this information from a JDBC driver?
You can find information about unique columns (defined as constraints or unique indexes), using DatabaseMetaData.getIndexInfo, passing true for the fourth parameter (unique).
For example
DatabaseMetaData md = connection.getMetaData();
// NOTE: You may need to use "PERSON"
try (ResultSet rs = md.getIndexInfo(null, null, "person", true, true)) {
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
String columnName = rs.getString("COLUMN_NAME");
if (indexName == null || columnName == null) {
continue;
}
System.out.printf("%s: %s%n", indexName, columnName);
}
}
Here you have a simple example based on MySql:
public class Test {
static final String DB_URL = "jdbc:mysql://localhost:3306/yourDatabase";
static final String USER = "----";
static final String PASS = "somePass";
static final String QUERY = "SHOW KEYS FROM YOUR_TABLE WHERE Key_name = 'PRIMARY'\n";
public static void main(String[] args) {
// Open a connection
final ArrayList<String> primaryKeyColumns = new ArrayList<>();
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
while (rs.next()) {
primaryKeyColumns.add(rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(primaryKeyColumns);
}
}
Look at the used query in this way you can fetch more specific information.

SQL Query Java Net Beans

Basically I have a table name java_db.Customer with the columns CustomerID,
Name, Address and FinanceOK.
Basically I want to write a simple query that says if FinanceOK = true JOptionPane.ShowMessage "Finance Accepted"
Otherwise FinanceOK = False JOptionPane.ShowMessage "Finance Declined".
What is the the best way to go about writing this query?
Now, there's a lot of information in your post that is missing but down and dirty here is how you might accomplish the task:
long customerID_Variable = 232; // .... whatever you have to provide customer ID number ....
String customerName = "John Doe"; // .... whatever you have to provide customer name ....
boolean financeOK = false; // default financing approval flag
String message = "Finance Declined!"; //default message
// Catch SQLException if any...
try {
// Use whatever your connection string might be
// to connect to your particular Database....
Connection conn = DriverManager.getConnection("jdbc:derby:c:/databases/salesdb jdbc:derby:salesdb");
conn.setAutoCommit(false);
// The SQL query string...
String sql = "SELECT FinanceOK FROM Customer WHERE CustomerID = " + customerID_Variable + ";";
// Although it is best to use the Customer ID to reference a
// particular Customer you may prefer to to use the Customer
// name and if so then use the query string below instead...
// String sql = "SELECT FinanceOK FROM Customer WHERE Name = '" + customerName + "';";
// Execute the SQL query...
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
//Retrieve the data from the query result set...
while (rs.next()) {
financeOK = rs.getBoolean("FinanceOK");
}
//Close everything...
rs.close();
stmt.close();
conn.close();
}
catch (SQLException ex) { ex.printStackTrace(); }
int msgIcon = JOptionPane.ERROR_MESSAGE;
if (financeOK) {
message = "Finance Accepted!";
msgIcon = JOptionPane.INFORMATION_MESSAGE;
}
JOptionPane.showMessageDialog(null, message, "Financing Approval...", msgIcon);

error in inserting data to database

Here's my code for createFood DA so that can insert to database. However , there is a nullPointerException at
pstmt.setString(2, food.getFoodName());
public static int createFood(Food food) {
// declare local variables
int orderID ;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - establish connection to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "INSERT INTO orderitems (orderId, foodName, foodPrice, quantity,) VALUES(?,?,?,? )";
pstmt = (PreparedStatement) db.getPreparedStatement(dbQuery);
orderID = getNextOrderId();
// step 3 - to insert record using executeUpdate method
try {
pstmt.setInt(1,orderID );
pstmt.setString(2, food.getFoodName());
pstmt.setDouble(3 ,food.getFoodPrice());
pstmt.setInt(4, food.getQuantity());
if (pstmt.executeUpdate() == 1)
return orderID;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return -1;
}
This is the code when i click on "orders".
private void actionPerformedOrder() {
//retrieve user input
String numPax = (String) cbNoPax.getSelectedItem();
String tableNo= (String)cb_tableno.getSelectedItem();
java.util.Date utilDate = new java.util.Date();
Date orderDate = new Date(utilDate.getTime());
System.out.println("Date " + orderDate);
orders = new Orders(Integer.parseInt(tableNo),Integer.parseInt(numPax), (java.sql.Date) orderDate, totalAmount);
int orderID = OrdersDA.createOrders(orders);
OrderItems od;
for (Food fd: foodList) {
od = new OrderItems(orderID, fd.getFoodName(), fd.getQuantity(), fd.getFoodPrice());
FoodDA.createFood(food);
}
I still cannot figure out the error. Anyone knows where went wrong ? Much help will be appreciated.
You have passed createFood() method food variable which i cant see declare anywhere
try
createFood(fd) according to your code.

JDBC How can I use a place holder in a prepared statement with a where clause?

I'm having a hard time understanding why this wont work, if I type the exact same thing straight into a MySQL console it accepts it but when ever I try to run it, it reports a syntax error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '6'' at line 1
All I'm trying to do is receive the data in the row with the member_id value of whatever the user inputs. For testing purposes the value is always 6, I have tried parsing it as int instead of a string, which gave the same error, and I tried just adding the ID variable onto the end of the string instead of using a place holder but it didn't like that much either.
Here is the code:
public class MemberDAO {
public PreparedStatement ps = null;
public Connection dbConnection = null;
public List<Member> getMembersDetails(String ID) throws SQLException{
List<Member> membersDetails = new ArrayList();
String getMembershipDetails = "SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members"
+ "WHERE member_id = ?";
try {
DBConnection mc = new DBConnection();
dbConnection = mc.getConnection();
ps = dbConnection.prepareStatement(getMembershipDetails);
ps.setString(1, ID);
ps.executeQuery();
ResultSet rs = ps.executeQuery(getMembershipDetails);
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String phoneNumber = rs.getString("phone_number");
String email = rs.getString("email");
String over18 = rs.getString("over_18");
String dateJoined = rs.getString("date_joined");
String dateExpired = rs.getString("date_expire");
String fines = rs.getString("fines");
Member m;
m = new Member(firstName, lastName, phoneNumber, email, over18, dateJoined, dateExpired, fines);
membersDetails.add(m);
} catch (SQLException ex){
System.err.println(ex);
System.out.println("Failed to get Membership Details.");
return null;
} finally{
if (ps != null){
ps.close();
}
if (dbConnection != null){
dbConnection.close();
}
} return membersDetails;
}
This is what's calling it:
private void btnChangeCustomerActionPerformed(java.awt.event.ActionEvent evt) {
customerID = JOptionPane.showInputDialog(null, "Enter Customer ID.");
MemberDAO member = new MemberDAO();
try {
List membersDetails = member.getMembersDetails(customerID);
txtFullName.setText(membersDetails.get(0) + " " + membersDetails.get(1));
} catch (SQLException ex) {
System.err.println(ex);
System.out.println("Failed to get Details.");
JOptionPane.showMessageDialog(null, "Failed to retrieve data.");
}
}
Any input is appreciated.
Your query is missing a space:
...fines FROM members"
+ "WHERE...
Will result in
FROM membersWHERE
Which is invalid SQL
Change it to
+ " WHERE....
your query is:
SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM
members WHERE member_id = ?
So between member and where you need a blank character
SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members WHERE member_id = ?

Problem in inserting data into Oracle database using JDBC

I am trying to insert data using prepared statement in oracle 10g database but I am getting "SQL Exception:General Error" while executing the code given below. I think the problem is either with the DATE field or PASSWORD field data retrieval. Please Help me through this. Thanks.
Student Table:-
Sid VARCHAR2(200) PRIMARY KEY CHECK(Sid>0),
Pass_word VARCHAR2(10) NOT NULL,
S_name VARCHAR2(20) NOT NULL,
G_name VARCHAR2(20) ,
Branch VARCHAR2(10) NOT NULL,
D_company VARCHAR2(20) ,
B_Percent INT NOT NULL CHECK(B_Percent<100),
twelth_percent INT NOT NULL CHECK(twelth_percent<100),
tenth_percent INT NOT NULL CHECK(tenth_percent<100),
Certify VARCHAR2(30),
Semester INT NOT NULL CHECK(Semester<9),
D_Birth DATE NOT NULL,
Sex VARCHAR2(6) NOT NULL
Code:-
int bpercent ;
int twelthpercent;
int tenthpercent;
int semester;
String studentID = null;
String studentpassword = null;
String studentname = null;
String Gname = null;
String branch = null;
String dcompany = null;
String certify = null;
String sex = null;
Date date = new Date(00-00-0000);
Connection connection = null;
try
{
// Load the JDBC driver
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:odbc:placement","siddharth","sid");
studentID = StudentID.getText();
spassword = PasswordField.getPassword();
studentname = NameField.getText();
Gname = GuardianField.getText();
branch = BranchField.getText();
dcompany = DcompanyField.getText();
bpercent = Integer.parseInt(BtechField1.getText());
twelthpercent = Integer.parseInt(TwelthField.getText());
tenthpercent = Integer.parseInt(TenthField.getText());
semester =Integer.parseInt(SemesterField.getText());
certify = CertificationField.getText();
date = (Date) DateTextField.getValue();
sex = SexCombo.getActionCommand();
PreparedStatement state = connection.prepareStatement("insert into student " +"(sid,pass_word,s_name,g_name,branch,d_company,b_percent,twelth_percent,tenth_percent,certify,semester,d_birth,sex)"+
"values(?,?,?,?,?,?,?,?,?,?,?,?,?)");
state.setString(1, studentID);
state.setString(2, spassword.toString());
state.setString(3,studentname);
state.setString(4,Gname);
state.setString(5,branch);
state.setString(6,dcompany);
state.setInt(7,bpercent);
state.setInt(8,twelthpercent);
state.setInt(9,tenthpercent);
state.setInt(10,semester);
state.setString(11,certify);
state.setDate(1, new java.sql.Date(date.getTime()));
state.setString(12,sex);
state.executeUpdate();
state.close();
JOptionPane.showMessageDialog(null,"Data Inserted","Information Messgage",JOptionPane.INFORMATION_MESSAGE);
connection.close();
}
catch (ClassNotFoundException e) {
// Could not find the database driver
JOptionPane.showMessageDialog(null,e);
}
catch (SQLException e) {
// Could not connect to the database
JOptionPane.showMessageDialog(null,e);
}
}
I believe you have a typo, you have:
state.setDate(1, new java.sql.Date(date.getTime()));
state.setString(12,sex);
And I think you want:
state.setDate(12, new java.sql.Date(date.getTime()));
state.setString(13,sex);
You've got certify and semester the wrong way round
In your insert sql string:
insert into (... tenth_percent,certify,semester,d_birth, ...)
in your
state.setInt(9,tenthpercent);
state.setInt(10,semester);
state.setString(11,certify);
state.setDate(12, new java.sql.Date(date.getTime()));
so it tries to set the semester column to a string, which is invalid.
Instead of using the lines:
`String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driverName);`
Use the line:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver);
Sometimes, the class cannot be read by the drivermanager, so you need to register the driver with the drivermanager.
Best of Luck!
Well! there was a mistake in the code...
Instead:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver);
Use:
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

Categories

Resources