How to update mysql database value from java netbeans - java

How to update mysql database value from java netbeans
I need to update one of my selected column value
this table has 6 column but I need to update one column only (6th column)
So how to do this -
I use this code -
connectDB();
try{
String value1 = txt_searchcode.getText();
String value6 = Final_stock_view.getText();
String sql = "Update tbl_codes set No='"+value1+"',Bin_Balance='"+value6+"'WHERE No='"+value1+"' ";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.execute();
JOptionPane.showMessageDialog(null, " Your new records Updated Succsessfully!!");
}catch(Exception e){
JOptionPane.showMessageDialog(null," Update Failed");
}
closeDB();
its running well without any errors, but nothing happen
So how to fix this...... (Examples)
Thanks

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.

MySQL DATA Truncation Error occuring from Java GUI application but not directly on MySQL

Using a java program, am trying to update 3 colums in a table (the same table) on click of a button but when i try, to run it, it generates an error.
This is the error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'javax.swing.jTextField[,20,34,14x29,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,borde'
And heres my code
private void SaveBTNActionPerformed(java.awt.event.ActionEvent evt) {
// method for treating patient
try{
String sql = "UPDATE `iClinic`.`Treatment` SET `ProblemDesc` = ?,`Comments` = ?,`RescheduleDate` = ? WHERE `Treatment`.`RegID` ='"+PRegIDTF+"'";
pst=conn.prepareStatement(sql);
pst.setString(1, descriptionTA.getText());
pst.setString(2, CommentsTF.getText());
String value = ScheduleDateDT.getDate().toString();
pst.setString(3, value);
pst.execute();
JOptionPane.showMessageDialog(null, "saved");
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
The mistake/ problem was that in the SQL statement, i had only included the name of the jtextfield withoud including the command or method to fetch d result o value in that jtextfield. so the solution/ correction would be as below;
String sql = "UPDATE iClinic.Treatment SET ProblemDesc = ?,Comments = ?,RescheduleDate = ? WHERE Treatment.RegID = '"+PRegIDTF.getText()+"'";

"all columns must be set before insert" error on a ResultSet insert with UCanAccess

I want to create an Access database connection using UCanAccess under Java 8. Here is my code:
String employeeName = endrollNameFields.getText();
String employeeAddress = endrollAddressFields.getText();
try
{
//------------CREATE CONNECTION TO DATA BASE--------------/
String DBPAD = "sourceFolder\\employeeTable2.mdb";
String DB = "jdbc:ucanaccess://" + DBPAD;
con = DriverManager.getConnection(DB, "", "");
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "select * from employeeTable2";
rs = st.executeQuery(sql);
rs.moveToInsertRow();
rs.updateString("Name", employeeName);
rs.updateString("Address", employeeAddress);
rs.insertRow();
st.close();
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql1 = "select * from employeeTable2";
rs = st.executeQuery(sql1);
JOptionPane.showMessageDialog(null, "<html>" + "<font color=\"#008000\">" + "<html><span style='font-size:1.5em'>Employee Successfuly Inserted to Data Base");
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
}
I made entries to my JTextField but when i click the button containing codes above this error message appears:
net.ucanaccess.jdbc.Ucanaccess SQLException:invalid cursor state: all columns must be set before insert
What is missing or lacking in my code?
UCanAccess uses HSQLDB as a "backing database", and HSQLDB requires that all columns in the insert row be given an explicit value before calling .insertRow(), including using rs.updateNull("ColumnName") to explicitly specify a NULL value. That's just the way it works.
This was discussed recently on SourceForge here. The requirement may be lifted in a future version of UCanAccess.
UPDATE
UCanAccess version 3.x, released in August 2015, has indeed removed the above requirement. Any columns not explicitly set in the insert row will contain the default value for the column (or NULL if the column is nullable and no default value is specified in the table definition).

jTable connected to MySQL button error

i have the following jframe :
and i wanna make the buttons work im still new to programming can someone help me please? i want the add row btn to add a new row to database, the update btn let me save changes and delete delete the selected row, also the jTextBoxes are connected to the database
i tried doing this to update :
Connection conn=null;
PreparedStatement pst = null;
try{
String value1=txt_cid.getText();
String value2=txt_carid.getText();
String value3=txt_aid.getText();
String value4=txt_rd.getText();
String value5=txt_bd.getText();
String value6=txt_bn.getText();
String sql="update booking set customer_id'"+value1+"',car_id'"+value2+"',agency_id'"+value3+"',return_date'"+value4+"',booking_date'"+value5+"',booking_number'"+value6+"',";
pst=conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "table updated");
}catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
but it didnt work out for me i get exception error
You haven't stated what the error is but UPDATE takes an equals operator for every parameter. Also use PreparedStatement placeholders to avoid SQL Injection attacks:
String sql = "update booking set customer_id=?, car_id=?,agency_id=?,return_date=?,booking_date=?,booking_number=?";
pst = conn.prepareStatement(sql);
pst.setInt(1, value1);
pst.setInt(2, value2);
... // set the other parameters
Read: UPDATE Syntax

adding new column to table with column name as present days date

I am new to java .I want to build simple java application for attendance management system.For doing this I want to create a new column into already existing table the column name should be present days date.I used date picker for getting present days date.
I had written following code for this,but the column name in table is setting as "+s1+".
This is my code:
String s="";
s=date.getText();//selected data from date picker
s.replace(".","_");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:vasu");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//System.out.println("ALTER TABLE attendance ADD "+s+" varchar(50);");
rs = st.executeQuery("ALTER TABLE attendance ADD '"+s+"' varchar(50);");
}
catch(Exception ex){
}
could any one help me
well thanks in advance.
Try this
executeUpdate return 1 if the query work properly otherwise it will return 0
String s="";
s=date.getText();//selected data from date picker
s.replace(".","_");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
ResultSet acrs;
String op = "jdbc:odbc:vasu";
Connection cnn = DriverManager.getConnection(op,"username", "password");
Statement mystmt = cnn.createStatement();
int successOrFailure = mystmt.executeUpdate("ALTER TABLE attendance ADD '"+s+"' VARCHAR(50)");
//executeUpdate return 1 if the query work properly otherwise it will return 0
}catch(Exception e)
{
System.out.println("Exception:"+e);
e.printStackTrace();
}

Categories

Resources