Java Swing: Insert JTable column into mysql database - java

I was trying to INSERT data into mysql database from java swing form where I have two textfield value and one table column value. There I am getting problem with my Insertion process. I am trying to Insert the rows of a jtable column into database, but I found there Inserted that value of last row in the database.
I did the following code.
String customer_name = nametf.getText();
String phone = phonetf.getText();
PreparedStatement ps;
ResultSet rs = null;
String salesQuery = "INSERT INTO `sales`(`Customer_Name`, `Phone`,`Items`) VALUES (?,?,?)";
try {
ps = my_con.getConnection().prepareStatement(salesQuery);
ps.setString(1, customer_name);
ps.setString(2, phone);
for(int i=0; i<table1.getRowCount();i++){
ps.setString(3, table1.getValueAt(i, 0).toString());
}
if(ps.executeUpdate() != 0){
JOptionPane.showMessageDialog(null,"\nSave Succesfully\n\n","Saved",1);
}
else {
JOptionPane.showMessageDialog(null,"\nCheck Error\n\n","Error",1);
}
}
catch (SQLException ex) {
Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
}

but I found there Inserted that value of last row in the database.
In your loop you keep setting the 3rd parameter.
You only invoke the executeUpdate(...) statement once so only the last row is updated.
You need to execute your SQL statement for every row in the table:
for(int i=0; i<table1.getRowCount();i++){
ps.setString(1, customer_name);
ps.setString(2, phone);
ps.setString(3, table1.getValueAt(i, 0).toString());
ps.executeUpdate();
}
Note you can also do a batch update of the database. Check out: updating mysql table using where parameter from jtable cell for an example of this approach. You will need to combine the code in the question with the code in the answer to see the full batch implementation.

Related

Foreign Key not getting the value of Id of Primary Key prints NULL

I'm working with my project just for a academic purposes where I encounter a SQL problem. Where the Foreign Key its not getting the value of inserted ID. For me to achieve 2nd Normal Form. I split out in an independent tables. And match them up using the SECTION_ID as foreign keys. Here where I create a two tables.
1st Table
2nd Table
SOURCE CODE:
String inputSectionName = Section_SectionName_TextField.getText();
int inputStudentLimit = Section_Student_Limit_ComboBox.getSelectedIndex();
String inputRoomAssign = Section_Student_Limit_ComboBox2.getSelectedItem().toString();
String inputAdviserAssign = Section_Student_Limit_ComboBox1.getSelectedItem().toString();
String inputSession = Section_Session_Settings_ComboBox.getSelectedItem().toString();
String inputYearLevel = Section_Session_Level_ComboBox.getSelectedItem().toString();
String inputSchoolYear = Section_SchooYear_ComboBox.getSelectedItem().toString();
String insertALLSECTION_LIST = "INSERT INTO ALLSECTIONS_LIST (SECTION_NAME)"
+ "VALUES (?)";
String insertALLSECTIONS_SETTINGS = "INSERT INTO ALLSECTIONS_SETTINGS (SECTION_POPULIMIT,ROOM_ASSGN,ADVISER_ASSIGNED,SESSION_ASSIGNED,YRLEVEL_ASSGN,SCHOOL_YEAR)"
+ "VALUES(?,?,?,?,?,?)";
try (Connection myConn = DBUtil.connect())//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
}//end of try
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTIONS_SETTINGS))//Prepared Statement
{
myPs.setInt(1,inputStudentLimit);
myPs.setString(2, inputRoomAssign);
myPs.setString(3, inputAdviserAssign);
myPs.setString(4, inputSession);
myPs.setString(5, inputYearLevel);
myPs.setString(6, inputSchoolYear);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null, "Insert Successful");
}//end of try
}//end of try
catch(SQLException e)
{
DBUtil.processException(e);
}//end of catch
When I run my query for the 1st Table it gives me output like this.
But when I run my query for the 2nd Table the SECTION_ID column gives a me null value.
Feel free to comment. If I miss something guide me where I go wrong. Thanks.
It looks like you're assuming the SECTION_ID column in your ALLSECTIONS_SETTINGS table will be automatically populated with the last primary-key value that was inserted into the ALLSECTIONS_LIST table. This doesn't happen.
What you need to do instead is to get the value that was automatically generated for the SECTION_ID column in the first PreparedStatement and set it in the second PreparedStatement.
Here's how to modify your first PreparedStatement to obtain the generated SECTION_ID:
int sectionId;
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST, Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
ResultSet generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next()) {
sectionId = generatedKeys.getInt(1);
} else {
throw new SQLException("No generated section ID returned");
}
}
The changes are:
add a new variable sectionId to hold the generated section ID,
add Statement.RETURN_GENERATED_KEYS to the call to prepareStatement on the first line. This tells your database to return the generated value for SECTION_ID.
fetch the generated-keys result-set from the statement and read the section ID out of it..
I'll leave it up to you to modify your second PreparedStatement to set the value for the SECTION_ID column when you insert into ALLSECTIONS_SETTINGS.

How to get value as integer from JTextField in swing?

Actually i'm using oracle jdbc type4 thin driver. And I'm creating registration form in swing with eclipse with following columns pid,name,addrs.
the problem is i'm getting only string value which method is ps.setString=(2,JTextfiled.getText());
but i'm not able get int value like ps.setInt(1.getxxx());
can anyone guide me how to insert int value to database.
//prepare query
String query1 ="insert into employee values(?,?,?,?,?)";
//create preapare Statement
ps = con.prepareStatement(query1);
//set params
ps.setString(1,textField.getText());
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
ps.setString(4,textField_3.getText());
ps.setString(5, textField_4.getText());
//execute query
int count = ps.executeUpdate();
if(count==0)
{
JOptionPane.showMessageDialog(null, "Record not Inserted");
}
else
{
JOptionPane.showMessageDialog(null, "Record inserted into database successfuly");
}
Use Integer.parseInt to convert your string to an int, then use PreparedStatement#setInt to set it on the statement for insertion. E.g.:
ps.setInt(1, Integer.parseInt(textField.getText()));
You'll want to catch NumberFormatException in case the values in the text fields are not valid integers.

How to write a single query for multiple data manipulation in mysql?

I have to insert values from jsp form to database table and to the same table I need to insert values for two columns from 2 different tables.
Here is the code:
public class ForgotPassWordDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public void createSecretQnA(ForgotPassWord forgotPassWord) {
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2)VALUES(?,?,?,?,?)"; // Here am inserting form values to database.
String sql1="INSERT INTO forgotpassword (CustId) SELECT CustId FROM signup";// Here am trying to get value from another table and insert
String sql2="INSERT INTO forgotpassword (LoginId) SELECT LoginId FROM login"; // Here am trying to get value from another table and insert
Connection conn = null;
try {
conn = dataSource.createConnection();
PreparedStatement ps = conn.prepareStatement(sql);
PreparedStatement ps1 = conn.prepareStatement(sql1);
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps.setInt(1, forgotPassWord.getId());
ps.setString(2, forgotPassWord.getSq1());
ps.setString(3, forgotPassWord.getAnSq1());
ps.setString(4, forgotPassWord.getSq2());
ps.setString(5, forgotPassWord.getAnSq2());
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
catch (NullPointerException e1){
}
finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
But on each executeUpdate() its incrementing and the values from the form are stored in one row and in the next row the values from the signup and login tables are getting stored. How to make all this get stored in a single row? Any help is appreciated.
You are doing 3 inserts, so at least 3 rows are created. Also, when you do SELECT CustId FROM signup, how can you ensure that only one and the right value of CustId is taken from signup table? With this query you are fetching all the CustId. Same goes for login table and query.
To merely resolve your problem you have to create a single query:
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2,CustId,LoginId)VALUES(?,?,?,?,?,(SELECT CustId FROM signup),(SELECT LoginId FROM login))";
^ ^ ^ ^
but I don't think you have thought this enough.
There should be something like:
SELECT LoginId FROM login WHERE CustId=? //Here I'm guessing, I don't know your tables.
The point is to get the correct value both in login table and signup table that corresponds to the user who forgot his password. This can be easily done with a WHERE clause (supposing your foreign key are setted correctly).
EDIT
As per your comment I'm going to clarify the way you should add your new user.
First of all you need to create the new user, so as soon as the information needed is sent and checked you insert a new row in signup table. But wait to execute the query.
You need the CustId. Because is an auto-increment column, you don't know which value MySQL created. You must fetch it and you can do it directly when you create the new user adding a parameter to the prepared statement:
PreparedStatement pstmt = conn.prepareStatement(sqlForNewUser, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
custId = keys.getInt(1);
Now you have the new user Id and can use it to insert the other values:
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2,CustId,LoginId)VALUES(?,?,?,?,?,(SELECT CustId FROM signup WHERE CustId = ?),(SELECT LoginId FROM login WHERE CustId = ?))";
//...
ps.setString(6, custId);
ps.setString(7, custId);

Java sql update row in database

I have got adding a member to the database working.
I am trying to work out how to update a row in the table using the same system of passing in the values just not adding a new row, just altering the row using the passed in username.
Here is my method for inserting a new member:
public static void insertMember(String username,String firstName)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES (?,?)");
st.setString(1, username);
st.setString(2, firstName);
st.executeUpdate();
}
catch (SQLException e)
{
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE)
{
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
You need to use an UPDATE command instead of INSERT command.
Take a look at SQL UPDATE statement.
You will need to provide some means by which you can identify the row which needs to be updated, but this is dependent upon the structure of your table
I have got adding a member to the database working. I am trying to work out how to update a row in the table using the same system of passing in the values just not adding a new row, just altering the row using the passed in username.
you need Update command
like
UPDATE Members set username='somename',firstname='firstname' where condition
Need to change SQL command instead of INSERT , uses UPDATE.
Below code will update username for matching firstname provided in where clause.
PreparedStatement st = connection.prepareStatement("UPDATE Members set username=? where firstName=?)");
st.setString(1, username);
st.setString(2, firstName);
int updateStatus=st.executeUpdate();

geting data from multiple table when selecting a row then clicking a button

I am try to run the code below but every time I run it, it don't work. Could any one please highlight what i am doing wrong?
What the code should do is:
I have to table in the database called r and another called sa, table r contain column said as a foreign key. in my java front end i have a Jtable in a jpanel and an update button in another jpanel. when the user select a row in the jtable and then click update. the tool will display data from r in text boxes as well as data from sa if the selected row in the jtable r have sa id as a foreign key.
the Code
if(updateClicked == true){
btnSubmit.setVisible(false);
btnUpdate.setVisible(true);
btnNew.setEnabled(false);
Statement st;
PreparedStatement ps;
ResultSet rs;
try {
String rid = table.getValue(0);
JOptionPane.showMessageDialog(null, rid);
String rq ="SELECT * FROM `r` WHERE 'r_id`=' "+rid+"'";
ps = Login.con.prepareStatement(rq);
rs = ps.executeQuery();
String saID = rs.getString(2);
String q = "SELECT sa.Argument FROM sa, r WHERE r.sid ="+sID ;
st = Login.con.createStatement();
rs = st.executeQuery(q);
String argu = rs.getString(1);
System.out.println(argu);
if (argu.isEmpty()==false){
btnAddSA.doClick();
txtaArg.setText(argu);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the Console output
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'R0004' in 'where clause'
First of all give your tables proper names. "r" and "sa" don't mean anything.
I don't know what the problem with your SQL is but I will suggest that you use a PreparedStatement. It makes it easier to code the SQL so you don't worry about delimiter type mistakes.
A basic example would be:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, "Name1" );
stmt.setString( 2, "Title1" );
stmt.executeUpdate();
You can search the forum or web for more information.

Categories

Resources