get exeption when try to update foreign key - java

im learning now mysql and jdbc and i got home work im trying to add a foreign key and i cant understant what is this exeption this is my code please if someone can explain me what the problem it will realy help me
package jdbc;
import java.sql.*;
public class JDBC_HW {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/newdatabase", "root", "admin")) {
try (Statement statement = connection.createStatement()) {
String newTable = "CREATE TABLE jb_student (id int not null auto_increment, name varchar(500), grade int, PRIMARY key(id));";
statement.executeUpdate(newTable);
}
String insertStudents = "INSERT INTO newdatabase.jb_student "
+ "( name, grade)"
+ " VALUES( ?, ?);";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertStudents)) {
for (int i = 0; i < 100; i++) {
preparedStatement.setString(1, "student" + i);
preparedStatement.setInt(2, i * 100);
preparedStatement.executeUpdate();
}
}
String printTable = "select * from newdatabase.jb_student";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(printTable);
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.print(" ");
System.out.print(resultSet.getString(2));
System.out.print(" ");
System.out.println(resultSet.getInt(3));
}
}
String update = "UPDATE jb_student SET name = 'nikita', grade = 100 where id = 1;";
try (Statement statement = connection.createStatement()) {
int countUpdates = statement.executeUpdate(update);
System.out.println("updated rows : " + countUpdates);
}
String searchByName1 = "select * from jb_student where name like '%1';";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(searchByName1);
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.print(" ");
System.out.print(resultSet.getString(2));
System.out.print(" ");
System.out.println(resultSet.getInt(3));
}
}
String newTable = "CREATE TABLE jb_courses (id int not null auto_increment, name varchar(500), PRIMARY key(id));";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(newTable);
}
String insertCourses = "INSERT INTO newdatabase.jb_courses "
+ "(name)"
+ " VALUES(?);";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertCourses)) {
for (int i = 0; i < 5; i++) {
preparedStatement.setString(1, "course" + " " + i);
preparedStatement.executeUpdate();
}
}
String addColumn = "ALTER TABLE jb_student ADD COLUMN course_id int not null AFTER id;";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(addColumn);
}
String addFk = "ALTER TABLE jb_student add FOREIGN KEY (course_id) REFERENCES jb_courses (id);";
try(Statement statement = connection.createStatement()){
statement.executeUpdate(addFk);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
im sitting on this long time and cant resolve this exeption i tryied everithing i could think of
and im still getting this exeption :
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`newdatabase`.`#sql-12f0_21`, CONSTRAINT `jb_student_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `jb_courses` (`id`))
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1333)
at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2106)
at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1243)
at jdbc.JDBC_HW.main(JDBC_HW.java:92)
im braking my head on this thank you for helping

Related

Why does my query works only for number<10?

I use this func when entering data. So I need to check is there an employee with this id in db. The same function I use for registration and this method works. But when it comes to integer numbers it checks only when it's under 10 (or maybe it's the first inserted value)
This is my code to check unique of id:
private int checkUnique() {
try {
Scanner scan = new Scanner(System.in);
id = scan.nextInt();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:...", "...", "...");
Statement st = connection.createStatement();
ResultSet res = st.executeQuery("select id_emp from employees");
while (res.next()) {
if (res.getInt("id_emp")==getId()) {
res.close();
st.close();
connection.close();
System.out.println("There is employee with this id");
System.out.println("Enter id");
checkUnique();
} else {
res.close();
st.close();
connection.close();
return id;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
And that how I use it in my code:
Statement st = connection.createStatement();
String sql = "INSERT INTO employees (id_emp, first_name, last_name, cnt_kids, cnt_dkids,is_single,added_by) " +
"VALUES (?, ?, ?, ?, ?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
System.out.println("Enter id");
id = checkUnique();
What's wrong with this?
For example this code ask to enter other id when id=2(it's realy on the table), but when I insert id=12(also in the table) it just skips.
My table:
CREATE TABLE `employees` (
`id_emp` int NOT NULL,
`first_name` varchar(30) DEFAULT NULL,
`last_name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`cnt_kids` int DEFAULT NULL,
`cnt_dkids` int DEFAULT NULL,
`is_single` bit(1) DEFAULT NULL,
`added_by` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id_emp`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Use a prepared statement
Here is some sample code:
public class SQLMain {
public static void main(String[] args) throws SQLException {
System.out.println("ID to check:");
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test");
PreparedStatement preparedStatement = connection.prepareStatement("select id_emp from employees where id_emp = ?");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
// we have a row
System.out.println("Found employee with id of: " + resultSet.getInt(1));
} else {
// no row found - therefore unique
System.out.println("not found");
}
resultSet.close();
preparedStatement.close();
connection.close();
scanner.close();
}
}

Dynamically add columns and column names Jdbc/MySql

Is there a way to add dynamically columns and column names to an existing table using jdbc?
For example:
If NumberOfColumns = 3, I want the column names to be "Column1", Column2", "Column3".
I tried to add dynamically some columns with the name of iterator just for testing my code but it gives me an SQL syntax error.
Below are some parts of my code I just described. If I remove the whole loop, the code works like a charm.
public class something {
//Some Variables Declaration///
//Number of columns in test table//
int NumberOfColumns = 3;
public static void main(String args[]) {
//..... SOME CODE....//
//Create database//
sql = "CREATE DATABASE mydb";
stmt.executeUpdate(sql);
//Create test table//
sql = "CREATE TABLE mydb.table "
+ "(id INTEGER not NULL ";
stmt.executeUpdate(sql);
//Add columns dynamically//
for (int i = 0; i < NumberOfColumns; i++) {
sql = "ALTER TABLE mydb.test ADD'" + i + "' VARCHAR(30)";
stmt.executeUpdate(sql);
}
stmt.executeUpdate(sql);
}
}
First of all you should to delete your stmt.executeUpdate(sql); after your loop, this can make a problem,
change this lines:
for (int i = 0; i < NumberOfColumns; i++) {
sql = "ALTER TABLE mydb.test ADD'" + i + "' VARCHAR(30)";
stmt.executeUpdate(sql);
}
stmt.executeUpdate(sql);
just with this:
for (int i = 0; i < NumberOfColumns; i++) {
colname = "Column" + i;
sql = "ALTER TABLE mydatabase.table ADD " + colname + " VARCHAR(30)";
stmt.executeUpdate(sql);
}
Because you can will get an error that the 3ed column exist
also the name of column not need 'id' you just need to remove the two quots
Here is an exemple can solve your problem:
Requires that you initialize a driver so you can open a communications channel with the database, after create your database your tables and your columns,
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class createdatabase {
//Number of columns in test table//
private static int NumberOfColumns = 3;
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "root";
static final String PASS = "mypass";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE mydatabase";
stmt.executeUpdate(sql);
sql = "CREATE TABLE mydatabase.table (id INTEGER not NULL)";
stmt.executeUpdate(sql);
String colname;
for (int i = 0; i < NumberOfColumns; i++) {
colname = "Column" + i;
sql = "ALTER TABLE mydatabase.table ADD " + colname + " VARCHAR(30)";
stmt.executeUpdate(sql);
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Exception = " + e);
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
System.out.println("Exception" + se);
}
}
}
}
Hope this can help you
You need a space after the keyword ADD in the alter statement. I would also recommend prefixing the column name rather than just using a number.
Can you post the SQL error as well, to help clarify what the error actually is.

jdbc help translating mapping char to string when updating a database

I am trying to map a particular character to show the full word so in this code below I have a translate method, a select method that is selecting from the remote database and update method that updates those column to my local database.
My remote database has a column called profile_ind this columns only has single chars B,C,F,P,S,W in the data, and once I do the update I want to be able to translate it to the full word only without the chars. B = BENIGN, C = CUSTOMER, F = FRAME, P = PPCOS, S = STANDARD, W = W-RED
And in my update method I want to call that translate method. cos_profile_type is the column on my local database that I want to update to either BENIGN, CUSTOMER, FRAME,PPCOS,STANDARD,W-RED depending on profile_ind column in the remote db. How can I implement it ? how can i call that translate method in the update method when I set the ? in that statement.
public static String translate(String indicator) throws Exception {
if (indicator == null || indicator.length() == 0) return "";
if (indicator.equals("B")) return "BENIGN";
if (indicator.equals("C")) return "CUSTOMER";
if (indicator.equals("F")) return "FRAME";
if (indicator.equals("P")) return "PPCOS";
if (indicator.equals("S")) return "STANDARD";
if (indicator.equals("W")) return "W-RED";
System.out.println(indicator);
return "";
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
java.util.Date date= new java.util.Date();
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag, profile_ind from COS_PROFILE"
+ " WHERE profile_id >= ? AND profile_id <= ? ;";
try {
dbConnection = getInformixConnection(); //connects to ICORE database
System.out.println("ICORE Select Statement: " + selectTableSQL);
//Gets the max profile_id record
statement = dbConnection.createStatement();
ResultSet r = statement.executeQuery("SELECT max(profile_id) AS rowcount FROM COS_PROFILE");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("COS_PROFILE table has " + maxCount + " row(s).");
preparedStatement = dbConnection.prepareStatement(selectTableSQL);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, maxCount);
// execute select SQL statement
rs = preparedStatement.executeQuery();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("inside the finally block ICORE " + new Timestamp(date.getTime()));
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
System.out.println("ICORE Statement Connection is closed");
}
if (preparedStatement != null) {
preparedStatement.close();
System.out.println("ICORE PreparedStatement Connection is closed");
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database ICORE Connection is closed");
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
dbConnection = getOracleConnection(); //connects to BIDS database
java.util.Date date= new java.util.Date();
//Gets the max profile_id record
statement = dbConnection.createStatement();
dbConnection.setAutoCommit(false);
ResultSet r = statement.executeQuery("SELECT count (*) AS rowcount FROM traffic_profile_temp");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("Traffic_profile_temp table before update has " + maxCount + " row(s).");
String updateTableSQL =
"UPDATE traffic_profile_temp SET pe_ingress_flag = ?, "
+ " pe_egress_flag = ?,"
+ " ce_ingress_flag = ?,"
+ " ce_egress_flag = ?, "
+ " cos_profile_type = ? "
+ " WHERE traffic_profile_id = ? ";
// execute update SQL statement
System.out.println("BIDS Update Statement: " + updateTableSQL);
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
System.out.println("Updating Bids Database in process ...");
try {
int rowCount = 0;
int expectedId = 1;
int first = 0;
while (rs.next()) {
String ingressflag = rs.getString("ingress_flag"); //BIDS column is pe_ingress_flag
String egressflag = rs.getString("egress_flag"); //BIDS column is pe_egress_flag
String ceingressflag = rs.getString("ce_ingress_flag"); //BIDS column is ce_ingress_flag
String ceegressflag = rs.getString("ce_egress_flag"); //BIDS column is ce_egress_flag
String profileind = rs.getString("profile_ind"); //BIDS column is cos_profile_type
int profileid = rs.getInt("profile_id"); //BIDS column is traffic_profile_id
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setString(5, profileind);
preparedStatement.setInt(6, profileid);
preparedStatement.addBatch();
rowCount++;
if(expectedId == profileid){
if(first == 0){
first = expectedId-1;
}
}
if(expectedId != profileid){
if(first > 0){
System.out.println ("Profile id "+first+" to "+(expectedId-1)+" update.");
first = 0;
}
System.out.println ("Profile id "+expectedId+" to "+(profileid-1)+" missing.");
expectedId = profileid;
}
expectedId++;
}
if(first > 0){
System.out.println("Profile id "+first+" to "+(expectedId-1)+" update.");
first = 0;
}
preparedStatement.executeBatch();
dbConnection.commit();
System.out.println("Record(s) Updated : " + rowCount + new Timestamp(date.getTime()));
} catch (SQLException e) {
System.out.println("Update records Failed!! " + e.getMessage());
} finally {
System.out.println("inside the finally block BIDS" + " timestamp " + new Timestamp(date.getTime()));
if (statement != null) {
statement.close();
System.out.println("BIDS Statement Connection is closed");
}
if (preparedStatement != null) {
preparedStatement.close();
System.out.println("BIDS PreparedStatement Connection is closed");
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database BIDS Connection is closed");
}
}
}

How to create a table in access database using java

i need to create a table in access database. For this i tried with the following code
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.execute("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
But it throws the following error " ERROR: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ".
It is possible with UCanAccess
con = ConnectMdb(homedirectory+"/"+"Centre.accdb");
if (con != null) {
Statement st3 = null;
try {
st3 = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
String sqlq3 = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
// System.out.println(sqlq1);
// ResultSet rs3 = null;
try {
st3.execute(sqlq3);
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
Try this.
Below Corrected Code may help you:
mistake in connection string and while creating table. need to use executeUpdate method
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.executeUpdate("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
The problem is on this line:
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
which you should change to:
String connURL = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
i.e. you need to remove the semi-colon between jdbc and odbc.

adding the values from gui to the database table

I am trying to update a table in the database where i m accepting fees from the students and maintaining the record of the amount received, total amount received, and the mode of payment etc.
my code is as follows:
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
if(!rs.next())
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}
}
Initially when i add new values i get it properly but when i am trying to update an existing row i get the error that i m making a duplicate entry for primary key id.
what condition should i check so that i come to know that the result set is not having that particular id value and new person is paying the fee??
This condition:
if(!rs.next())
is being checked outside the while loop. This condition is always true and will try to insert a record even if update has taken place.
To avoid this, i suggest using a flag variable. Once an update has occurred, set the value of this flag to 1.
Check if it has been made 1 instead of if(!rs.next()) and go inside.
You're two if statements are colliding...
// If this is true...
if(rs.next()) {
// ...
// Looping till the it's false...
while(rs.next()) {
// ....
}
}
// Will mean that this is false...
if(!rs.next())
You should be using an else
if(rs.next()) {
// ...
while(rs.next()) {
// ....
}
} else {...}
Updated
After an enlightening conversion with Aashray (thanks), we've concluded that your logic is broken
Rather then manually trying to find the record manually by match the id's let the SQL database do it for you.
Instead of....
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
You should be using...
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
This will return a ResultSet that is either empty (no matches) or with (hopefully) one row.
From there, calling rs.next() will now let you branch of between an update or insert correctly.
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, "root", "17121990");
System.out.println("connected!");
String firstname = pay_enter_firstname.getText();
String lastname = pay_enter_lastname.getText();
String amt = pay_enter_amt.getText();
int amount = Integer.parseInt(amt);
String day = pay_enter_date.getText();
String cheque_no = pay_enter_chequeno.getText();
String mode = pay_enter_mode.getText();
int totalamount = 10000;
int bal_amt = totalamount - amount;
String remark = pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
if (rs.next()) {
int amtrecvd2 = rs.getInt(2);
bal_amt = totalamount - (amtrecvd2 + amount);
String updt = "UPDATE payment SET Amountreceivd=" + (amtrecvd2 + amount) + ",lastamtreceived=" + amount + ",dte='" + day + "', balance_amt =" + bal_amt + " WHERE id =" + id + ";";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
} else {
String str = " INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES (" + id + ",'" + firstname + "','" + lastname + "'," + amount + ",'" + day + "'," + amount + ",'" + mode + "','" + cheque_no + "'," + bal_amt + "," + totalamount + ",'" + remark + "')";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
} catch (ClassNotFoundException | SQLException | NumberFormatException e) {
e.printStackTrace();
}
}
I think this may help you
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
else
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}

Categories