Inserting selected row into mysql - java

EDITED I´ve changed the SQL code and it works, but I get the exception:
"cannot set a null tableModell
I´ve seen many very similar examples but not the one I need.
Therefore here we go:
It´s simple - In a InternalFrame I insert Code, ProjectName, Teamleiter, Description and click "Teilnehmer" to list all members of all projects from a table "tbl_teinehmer". Just the Lastname is shown.
So, I insert the correspondent data into the fields, list the projectmembers and select the members who will take part of this new project I´m creating.
In order to insert the data and the selected row from "teilnehmer" into a new Table:
private void buttonAnlegenActionPerformed(java.awt.event.ActionEvent evt) {
String data = tbl_teilnehmer.getValueAt(tbl_teilnehmer.getSelectedRow(), 0).toString();
String sql = "INSERT INTO TBL_PROJETO (PROJEKT_ID, PROJEKTNAME, TEAMLEITER, BESCHREIBUNG,**TEILNEHMER**)"; //now it works but I get the exception: cannot set a null TableModell.
+ " VALUES(?,?,?,?,?)";
menu = new HauptMenu();
try{
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, ct.getText());
pst.setString(2, nt.getText());
pst.setString(3, st.getText());
pst.setString(4, beschreibungText.getText());
pst.setString(5, data);
pst.execute();
menu.listaProjetos();
JOptionPane.showMessageDialog(null, "Projekt added to Database");
}
catch(Exception e){
System.out.println(e);
}
try{
conn.close();
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
ct.setText("");
nt.setText("");
st.setText("");
}
This is the error:
java.sql.SQLException: Parameter index out of range (5 > number of parameters, which is 4).
Maybe the problem is by PreparedStatemend declaration.
I´ve set
pst.setString(5, data);
as it would recognize the selected row from the variable data but I guess it´s wrong.

do it as follows
pst.setString(0, ct.getText());
pst.setString(1, nt.getText());
pst.setString(2, st.getText());
pst.setString(3, beschreibungText.getText());
pst.setString(4, data);

Thank you for helping me!
I solved the problem first by changing the SQL declaration:
First at I´ve placed '"+data+"', which is an placeholder(If I´m not mistaken) but I wanted to set the selected row into the respective column in DB.
Therefore I´ve changed it to the columnname: TEILNEHMER and set another questionmark '?' as VALUE.
It worked but I still got the error>> cannot set a null TableModel
and under this error >> Unsupported collation 'Latin7' or smth like that.
So I´ve set the Collation of my table from Lati7 to TableDefault and now it works entirely.
THANK YOU ALL AGAIN FOR HELPING ME!

There is no placeholder for 5th parameter in your sql query:
String sql = "INSERT INTO TBL_PROJETO (PROJEKT_ID, PROJEKTNAME, TEAMLEITER, BESCHREIBUNG,'"+data+"')"
+ " VALUES(?,?,?,?,?)";

Related

How can I prevent duplicate entries in Jtable and MYSQL(database)?

Well the main problem here is, the detection of the duplicate entries in the Jtable, the Detection of duplicate entries will work when your enter the SAME/IDENTICAL data for the third time. It would not work in the second time and duplicate.
how can i add a unique constrain in my mysql? i dont know how to do it. Please let me have a specific instructions on how to execute it
2nd try (duplicate)
3rd try(the detection works)
database
JAVA NETBEANS
DATABASE: MYSQL
I think the problem would be the try-catch part which is the part that I dont understand. Thank You in Advance.
Heres my codes:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String first = firstname.getText();
String last = lastname.getText();
String gen = gender.getText();
String strand = cboStrand.getSelectedItem().toString();
String aged = age.getText();
String add = address.getText();
try{
String sql;
sql = "INSERT INTO idusjavanew"
+ "(fname,lname,sex,strand,age,address)"
+ "VALUES (?,?,?,?,?,?)";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/idusjavanew?zeroDateTimeBehavior=convertToNull","root","");
pst = con.prepareStatement(sql);
pst.setString(1, firstname.getText());
pst.setString(2, lastname.getText());
pst.setString(3, gender.getText());
pst.setString(4, cboStrand.getSelectedItem().toString());
pst.setString(5, age.getText());
pst.setString(6, address.getText());
String selectQuery;
selectQuery = "select * from idusjavanew where fname ='"+first+"' and lname='"+last+"'";
System.out.println(selectQuery);
rs = pst.executeQuery(selectQuery);
System.out.println(rs.next());
if (rs.next()==false){
pst.executeUpdate();
JOptionPane.showMessageDialog(null , "Information has been recorded!");
showTableData();
}
else{
JOptionPane.showMessageDialog(null,"Information already added!");
showTableData();
}
}
catch(HeadlessException | SQLException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
showTableData();
}
You are calling next() twice on your result set once in print statement and once in if, that is causing the issue.
So according to your current code if you already have an entry the 1st call to next() will point it to that entry and the second call will return false. That is why it detects duplicate on third row entry.
So just remove System.out.println(rs.next()); and your code should work as intended.

Insert new Value in MySQL in same Cloumn (Java/Code)

I am working on a little project.
Now I don't know, how to "replace" a old value in the mysql table.
Here you can see the table:
Thats my methods:
MySQL.update("INSERT INTO OnlineServer (Name) VALUES ('" + API.getServerFreeServer() + "');");
public static void update(String qry) {
try {
java.sql.Statement st = con.createStatement();
st.executeUpdate(qry);
st.close();
} catch (SQLException e) {
connect();
e.printStackTrace();
}
}
The problem now is, if I update the mysql, it dont replace the value in the column "Name". It just add a new Value under the old Value. The table is Going to be too huge if I Update every 5 seconds.
I need exactly one value in the column "Name".
So I have tryed to replace the insert but it doesn't work for me.
Maybe you have some ideas?
Sorry for my bad English, I'am German.
It sounds like you want to do an update here of the table, rather than an insert:
String sql = "UPDATE OnlineServer Set Name = ?";
PreparedStatement ps = dbConnection.prepareStatement(sql);
ps.setString(1, API.getServerFreeServer());
ps.executeUpdate();
By the way, your current query is doing raw string concatenation, making it prone to typos as well as SQL injection. I have used a prepared statement above, which is the most desirable way to execute a query using JDBC.
INSERT operation is for adding new record only and thus irrespective of you specify single column or 1million column it will add a new record. You actually need an UPDATE statement saying
UPDTE OnlineServer SET Name = <value>
You might also want to check INSERT ... ON DUPLICATE KEY UPDATE

Writing multiple where clauses in Java using Mysql

below is code is a code i wrote to get the value of 'monthly Depreciation' when i select the row on my j Table by either mouse-clicked or key-pressed. but it only selects the first value for 'monthly depreciation' when i click on the rows or key-press.the problem i know is coming from the where statement but can't seem to get around it.
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP)
{
try{
int row =dep_report.getSelectedRow();
String Table_click=(dep_report.getModel().getValueAt(row, 0).toString());
String sql ="select Date_Acquired 'Date Acquired',Serial_Number 'Serial Number',"
+ " Description 'Description',Cost_Of_Acquisition 'Cost Of Acquisition',"
+ "Monthly_Depreciation 'Monthly Depreciation',Accumulated_Depreciation 'Accumulated Depreciation',Net_Book_Value 'Net Book Value'"
+ ",asset_update.Branch_Area 'Branch Area',Depts_name 'Department Name' ,User 'User',"
+ "Status 'Status' from items,asset_update where items.items_No = asset_update.items_No &&'"+Table_click+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Monthly Depreciation");
MonthlyDep.setText(add1);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
I would really appreciate the help thank you.
In your sql
where items.items_No = asset_update.items_No &&'"+Table_click+"'";
&& wont work for sql and you might need
where items.items_No = asset_update.items_No and items.someThing= '"+Table_click+"'";
Please use Java naming conventions and give proper names to things Table_click is a horrible variable name.
But can you describe what is in your table model in the 1st column of the selected row?
You seem to append that to your query and if it does not contain a valid SQL part, this will not work well with your statement. In a where clause you usually check a column against a value. I doubt that your table model has this written there, more likely you just have the value in your table model at this position.
Also make sure to properly use prepared statements. Never put the values directly in the SQL string you create or you create the perfect entry point for SQL injection. Assign the values instead once you have created the statement with something like this: pst.setString(1, Table_click);

Java Update clause not updating sqlite database

I am making a GUI and I need to update one column called "OCCURRENCES" whenever a patient needs help. I am using Netbeans (Java). For some reason I am not getting any errors. But My table does not Update. The executeUpdate is returning '0'. I have close all my result set statements and prepared statements at the end of the 'try', 'catch'.Also any other updates like updating from textfields, insertion of new patient and deleting patient from a table is working fine; just having problem with updating this column which initial value I have set to be zero whenever an occurrence happens I would like to call this method to increment value on column. I'm just learning to use sqlite, and I am really confuse please help here is the part of the code I am having problems with, Also it reaches the JOPtionPane message successfully.
try
{
conn = javaConnect.ConnectDB();//Returns Connection
PreparedStatement pst = conn.prepareStatement("UPDATE PEMs SET OCCURRENCES = ? "//1
+ "WHERE ROOM = ?");//2
pst.setInt(1, 1);
pst.setInt(2,1);
pst.executeUpdate();
int updated=pst.executeUpdate(); // get count to see if anything was updated
System.out.println("OCC" + updated);
JOptionPane.showMessageDialog(null, "SUCCESSFULL OCCURRENCE");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error UpdateOccurence :" + e);
e.printStackTrace();`enter code here`
}finally {
try{
rs.close(); pst.close(); }
catch(Exception e) { } }

How to get the Generated insert ID in JDBC?

My source code has the following structure:
SourceFolder
AddProduct.jsp
Source Packages
-Controller(Servlets)
SaveProduct.java
-Model(Db Operations)
ProductDbOperations.java
I am inserting a new product into the product table and at the same time I am inserting an entry into product_collection table (product_id | collection_id).
To insert an entry into the product_collection table i need to get generated id from product table. After that a new entry is inserted into the product_collection table.
Also, I am not using any Framework and am using Netbeans 7.3.
Problem:
A new entry is inserted into the product table with this piece of code
IN: ProductDbOperations.java
try
{
this.initConnection(); // Db connection
pst = cn.prepareStatement("INSERT INTO product values('"+name+"', "+quantity+", "+price+")");
rs = pst.executeUpdate();
}
catch(SQLException ex)
{
}
I Also used the solution at following link which doesn't works for me.
I didn't got any SQL exception
How to get the insert ID in JDBC?
so help me find out why this code not working for me .
Thanks a million.
Not all drivers support the version of getGeneratedKeys() as shown in the linked answer. But when preparing the statement, you can also pass the list of columns that should be returned instead of the "flag" Statement.RETURN_GENERATED_KEYS (and passing the column names works more reliably in my experience)
Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. The way you do it, will still leave you wide open to SQL injection.
// run the INSERT
String sql = "INSERT INTO product values(?,?,?)";
pst = cn.prepareStatement(sql, new String[] {"PRODUCT_ID"} );
pst.setString(1, name);
pst.setInt(2, quantity);
pst.setInt(3, price);
pst.executeUpdate();
// now get the ID:
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
long productId = rs.getLong(1);
}
Note that the column name passed to the call is case-sensitive. For Oracle the column names are usually uppercase. If you are using e.g. Postgres you would most probably need to pass new String[] {"product_id"}
The way you are using is not the proper way of using preparedstatement
use the following way
pst = cn.prepareStatement("INSERT INTO product values(?,?,?)");
pst.setString(1,name);
pst.setInt(2,quantity);
pst.setInt(3,price);
pst.executeUpdate();
Yes there is a way to retrieve the key inserted by SQL. You can do it by:
Using Statement.RETURN_GENERATED_KEYS in your previous insert and get the key which can be used in further insert
e.g:
String query = "INSERT INTO Table (Col2, Col3) VALUES ('S', 50)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Categories