No error is showing when i click the button but the table on the database doesn't update.
String heh = jLabel17.getText();
try {
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch (SQLException err) {
System.out.println(err.getMessage() );
}
You have messed up the query totally,
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
should be,
stmt.executeUpdate("UPDATE books SET availability='Unavailable' where Book_title='"+heh+"' ");
It is advisable to print query before you execute , as that avoids common mistakes. Also try to use Prepared Statements as yours is vulnerable to sql injection
Read this Prepared Statements and JDBC Drivers
AFTER HOURS OF RESEARCH, I FOUND THE SOLUTION, I REPLACED THIS
String heh = jLabel17.getText();
try{
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch(SQLException err){
System.out.println(err);
}
WITH THIS CODE
String heh = jLabel17.getText();
try{
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Dafuq7","Dafuq7","Dafuq7");
// Creating Statement for query execution
stmt = con.createStatement();
// creating Query String
String query = "UPDATE books SET availability='NOT AVAILABLE' WHERE book_title='"+heh+"'";
// Updating Table
int rows = stmt.executeUpdate(query);
System.out.println(rows + " Rows Updated Successfully....");
} catch (Exception e) {
System.out.println(e.toString());
}
Related
I am trying to use variable in select query with like clause but getting an error like invalid identifier. Here is my method...
private void searchBooks(){
try{
String SEARCHFORTHIS=Find_Book_Field.getText();
pst=conn.prepareStatement("SELECT * FROM BOOK WHERE NAME LIKE '%'+ SEARCHFORTHIS +'%'");
rs=pst.executeQuery();
Show_All_Books.setModel(DbUtils.resultSetToTableModel(rs));
}catch(SQLException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null,e);
}
}
NEVER use string concatenation to build a SQL statement with user-supplied text values.
Well, unless you really want your code to be susceptible to SQL Injection attacks, allowing a hacker to steal your data and delete your tables.
You're already using PreparedStatement, so use it right.
You should also use try-with-resources for correct resource management.
private void searchBooks() {
String SEARCHFORTHIS = Find_Book_Field.getText();
String sql = "SELECT * FROM BOOK WHERE NAME LIKE ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "%" + SEARCHFORTHIS + "%");
try (ResultSet rs = stmt.executeQuery()) {
Show_All_Books.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (SQLException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null,e);
}
}
Try this
try{
String SEARCHFORTHIS=Find_Book_Field.getText();
pst=conn.prepareStatement("SELECT * FROM BOOK WHERE NAME LIKE '%"+ SEARCHFORTHIS +"%'");
rs=pst.executeQuery();
Show_All_Books.setModel(DbUtils.resultSetToTableModel(rs));
}catch(SQLException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null,e);
}
}
Made changes in SELECT query only. you have not properly closed the double quote in it.
Note:
completely agree with Andreas, we should use Preparedstatment, in this kind of scenarios, to prevent SQL Injection attacks.
please I have a little problem with the transfer of patient records for data at the table
the code using it :
try {
//Statement mystt = (Statement) conn.createStatement();
int row= affichagetable_pt.getSelectedRow();
String Table_click=( affichagetable_pt.getModel().getValueAt(row, 0).toString());
String query="insert into archives_pt (numfiche_pt,datefiche_pt,nom_pt,prenom_pt,datenaissance_pt,gsm_pt,cin_pt,profession_pt,sexe_pt,adresse_pt,nomsons_pt,cinsons_pt) select numfiche_pt,datefiche_pt,nom_pt,prenom_pt,datenaissance_pt,gsm_pt,cin_pt,profession_pt,sexe_pt,adresse_pt,nomsons_pt,cinsons_pt from patient where patient.numfiche_pt='"+Table_click+"'";
pst=conn.prepareStatement(query);
rs=pst.executeQuery();
JOptionPane.showMessageDialog(null,"Effacement OK");
pst.close();
} catch (Exception e2) {
// TODO: handle exception
JOptionPane.showMessageDialog(null,e2);
}
the error :
e2 message is "the statement did not return the result set"
Use execute statement for data manipulation like insert, update and delete and executeQuery for data retrieval like select.
replace
pst.executeQuery
with
pst.execute();
End your INSERT statement with a semi-colon before starting your SELECT statement:
...,cinsons_pt); select...
I want to select all data from database table between given 2 specific dates and add that data to a jtable.
Below is my code to retrieve data from the database; But all the data is not shown by this code .. What is the error I done here?
private void updateTable(){
String fday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
String tday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN '"+fday+"' AND '"+tday+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
tbl.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : "+ex);
}
}
Leverage the JDBC drive and it's ability to map between data types from Java to the database, leverage the power of the PreparedStatement
I'm using prepared statements pst is the prepare statement
BUT, you're not using it properly, see Using Prepared Statements for more details.
Start by getting the Date value from the date picker (I'm guessing here, but I assume they have some kind of getDate method) and then bind the values to the wildcard columns of the query, for example...
Date fday = day_chooser.getDate();
Date tday = day_chooser.getDate();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN ? AND ?";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setDate(1, new java.sql.Date(fday.getTime()));
pst.setDate(2, new java.sql.Date(tday.getTime()));
try (ResultSet rs = pst.executeQuery()) {
tbl.setModel(DbUtils.resultSetToTableModel(rs));
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : " + ex);
ex.printStackTrace();
}
Don't assume anything about the format, this will just cause you no end of grieve if you ever have to change databases
public class StudentDataPersistence {
public void insertStudentInfo(Student student) {
String url = "jdbc:oracle:thin:#localhost:1521:XE";
String username = "system";
String password = "Data03#";
Connection connection = null;
//Statement statement = null;
try {
//Step 1 : Register JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Step 2 : Open a connection
System.out.println("Connecting to a selected database...");
connection = DriverManager.getConnection(url, username, password);
if (connection != null) {
System.out.println("Connected to oracle");
}
//Step 3 : Write code to map Java Object to the Student_Info table
System.out.println("Inserting records into the database");
statement = connection.createStatement();
String sql = "insert into Student_Info " +
"VALUES(student.getName(),student.getRoll_no(),student.getAddress(),student.getPhone_no())";
statement.executeUpdate(sql);
System.out.println("Inserted student information into the database");
} catch (SQLException se) {
//handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
//Handle errors for Class.forName
} finally {
System.out.println("Inside the finally block");
//finally block used to close resources
try {
statement.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("!GoodBye");
}
public static void main(String[] args) {
Student student = new Student("Bavin", 1, "Umar Nagar", "89898989809");
StudentDataPersistence obj = new StudentDataPersistence();
obj.insertStudentInfo(student);
}
}
The error it shows it :
Connecting to a selected database...
Connected to oracle
Inserting records into the database
java.sql.SQLException: ORA-00904: "STUDENT"."GETPHONE_NO": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:189)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:242)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:554)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1478)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:888)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2076)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1986)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2697)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1035)
at org.core.hibernate.reason.StudentDataPersistence.insertStudentInfo(StudentDataPersistence.java:52)
at org.core.hibernate.reason.StudentDataPersistence.main(StudentDataPersistence.java:80)
Inside the finally block
!GoodBye
All the answers (those of you who illustrate it with an oracle query) in reply were wrong.
Kindly do have a look at it before posting.
the correct one i got when i posted another thread regarding the same:
String query = "insert into Student_Info(name,roll_no,address,phone_no) VALUES('"+student.getName()+"',"+student.getRoll_no()+",'"+student.getAddress()+"','"+student.getPhone_no()+"')";
you have commented out your Statement object definition. So the statement object is unknown when you're using it.
uncomment this line:
//Statement statement;
And as earlier pointed out by #putaro, you need to quote certain parts of your SQL query.
String sql = "insert into Student_Info " +
"VALUES("+student.getName()+","+student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
This is to insert the actual object values into the query. Things within the quote would be inserted as it is.
Error ORA-00904 means Oracle does not know the identifier "STUDENT"."GETPHONE_NO" it looks like you are trying to insert some value to a column named "GetPhone_NO" to Table "Student" from your SQL. so you should check your SQL and table structure again
I see there are two problems in the code.
Currently your code is not using the student object while making the query. All student.getName() etc call taken as plain strings rather than method calls that returns the appropriate values.
Second it would be better to write the query in the following form. It will avoid silly errors because of the structure of the tables.
"INSERT INTO student_info(name,roll_no,address,phone) VALUES("+
student.getName()+"," +
student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
Even better is if you use prepared statement like
Try changing the query like
"INSERT INTO student_info(name,roll_no,address,phone) VALUES(?,?,?,?)"
and then set the parameter values.
What I want to do is execute multiple two queries and the show the results in a jTable. I tried using the UNION but weird results came out in the table like this:
[B#58f67fc 3
[B#9f3d43e 1
[B#66f3378c 3
[B#69c3fd21 4
[B#421fb7c6 3
instead of actual usernames
I already looked at: mysql insert multi row query result into table?
This is what I used:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection CC = DriverManager.getConnection("jdbc:mysql://localhost:3306/pulsedb", "root", "carrizo");
String getID = "SELECT stuff_id,med_specialty FROM mstuffinfo UNION ALL SELECT username,user_level FROM mstufflogin";
PreparedStatement PS = CC.prepareStatement(getID);
ResultSet RS = PS.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(RS));
}
catch(SQLException SQ)
{
SQ.printStackTrace();
SQ.getErrorCode();
}
catch (ClassNotFoundException ex) {
Logger.getLogger(PulseSTUFFLIST.class.getName()).log(Level.SEVERE, null, ex);
}
}