Save data to mysql database in java - java

hello everyone i need your help.. i'm trying to save data to mysql database in java using netbeans IDE my source code doesn't want to run"it gives me an error that says"Java.lang.NullPointerExcepion
here's my source code..
try{
String sql = "Insert into clients(username,Id_number,surname,fullname,age,diagnose) values(?,?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txt_surname.getText());
pst.setString(2, txt_fullname.getText());
pst.setString(3, txt_age.getText());
pst.setString(4, txt_diagnose.getText());
pst.setString(5, txt_ID.getText());
pst.setString(6, txtusername.getText());
//pst.setString(7, txt_password.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Saved");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}

This code is clear and ok. the only possible var causing trouble is con. So try to add a sysout print statement before all con == null and look if it is true, then check whats missing on the connection setup

Related

Java - get the value of selected list item

how can I get the value of an list?
This are my two lists and after selecting these two values from the list(as marked) I want to insert these two elements(strings) into my database at this postition in my code:
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, txtFieldName.getText());
pst.setString(2, txtFieldNumber.getText());
// pst.setString(3, listDay.);
And at the last position I want to select the value which the user selects in the UI two list :
JButton btnNewButton_2 = new JButton("Speichern");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.sql.Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/dblabor","root","");
String query = "INSERT INTO Teach(Prof,Laborname,Room,Day,Time) VALUES(?,?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, txtFieldName.getText());
pst.setString(2, txtFieldLaborname.getText());
pst.setInt(3, Integer.parseInt(txtFieldRoom.getText()));
pst.setString(4, (String) listDay.getSelectedValue());
pst.setString(5, (String) listTime.getSelectedValue());
pst.execute();
pst.close();
JOptionPane.showMessageDialog(null, "Succssesfull");
}
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "Wrong");
}
`
Thank you all in advance.
how can I get the value of an list?
You have been told to simply use:
Object value = list.getSelectedValue();
System.out.println(value);
Did you display the value?
Have you read the tutorial on JDBC Database Access?
I believe you need to use executeUpate() method of the PreparedStatement to change the data.
If you are using Swing, try method javax.swing.JList#getSelectedValue to get value from JList object.

Inserting selected row into mysql

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(?,?,?,?,?)";

Inserting in database using java1001

I always get this error every time i try to save or execute the query.
I can't work it out,maybe alittle advice will help.
java.sql.SQLException: can not issue data manipulation statements with
executeQuery()
here is my code for inserting into my database.
Connection conn=null; ResultSet rs = null,rs1=null; PreparedStatement
pst = null,pst1=null;
DefaultTableModel model= (DefaultTableModel)tbl_stud.getModel();
try{
String sql="INSERT INTO students (id_num,fname,mname,lname,course,gender,year,username,password) VALUES(?,?,?,?,?,?,?,?,?);";
model.setNumRows(0);
pst=conn.prepareStatement(sql);
String id=txt_idnum.getText();
pst.setString(1,id);
String f=txt_fname.getText();
pst.setString(2, f);
String m=txt_mname.getText();
pst.setString(3, m);
String l=txt_lname.getText();
pst.setString(4, l);
String crs=cmb_course.getSelectedItem().toString();
pst.setString(5, crs);
String gen=cmb_gender.getSelectedItem().toString();
pst.setString(6, gen);
String year = cmb_year.getSelectedItem().toString();
pst.setString(7, year);
String uname=txt_username.getText();
pst.setString(8, uname);
String pass=txt_password.getText();
pst.setString(9, pass);
pst.executeQuery(sql);
JOptionPane.showMessageDialog(null, "Saved!","",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e,"",JOptionPane.ERROR_MESSAGE);
}
you need to use pst.executeUpdate rather then pst.executeQuery
The exception message says it all:
can not issue data manipulation statements with executeQuery()
Instead, you should use executeUpdate(). Additionally, if you've already prepared the statement, you should use the execute variants that do not receive a String argument. Those are inherited from Statement and should not be used with PreparedStatements (and yes, this does go a long way towards showing that JDBC is a terrible API).
pst.executeUpdate();
As an additional sidenote, you should drop the semicolon (;) and the end of your insert statement. Depending on the exact driver and RDBMS you're using it may either be redundant or just plain out wrong.

How do I insert last_insert_id using preparedStatement?

I am facing difficulty in inserting " last_insert_id" in my prepared statement.I got how to select the last_insert_id in prepared statement like below:
PreparedStatement getLastInsertId = con.prepareStatement("SELECT LAST_INSERT_ID()");
When I use the same procedure for inserting last_insert_id in my preparedstatement like this:
1. PreparedStatement pst = con.prepareStatement("insert into introducer_table values(?,?,?,?)");
2.
3. //introducer details into database
4. pst.setString(1,LAST_INSERT_ID());
5. pst.setString(2, nameofintroducer);
6. pst.setString(3, accountno);
7. pst.setString(4, signofintroducer);
Im getting 'null' value in the first column.can any one help me to come out from this problem
If your doing both the save actions at a time use getGeneratedKeys(), It's pretty much java.
I'm not a SQL guru, but here I found a way to get the generated id using getGeneratedKeys()
long generatedId= 0L;
statement = con
.getConnection()
.prepareStatement(
"insert into new_user set name= ? , contact= ? , ....",
statement.RETURN_GENERATED_KEYS);
statement.setString(1, "examplename");
statement.setString(2, "examplecontact");
------
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);// here is your generated Id , use it to insert in your introducer_table
}
PreparedStatement pst = con.prepareStatement("insert into introducer_table values(?,?,?,?)");
//introducer details into database
pst.setString(1, generatedId);
pst.setString(2, nameofintroducer);
pst.setString(3, accountno);
pst.setString(4, signofintroducer);

how to insert date in mysql using jsp?

this is my edited code...
java.sql.Timestamp sqlNow = new java.sql.Timestamp(new java.util.Date().getTime());
stmt = con.createStatement();
//stmt.executeUpdate("INSERT INTO cregn values('"+appno+"','"+usname+"','"+upwd +"','"+fname+"','"+mname+"','"+lname+"','"+dob+"','"+gend+"','"+faname+"','"+saddr+"','"+caddr+"','"+staddr +"','"+pin+"','"+cno+"','"+email+"','"+occ+"','"+secques+"','"+answer+"','Processing','"+sqlNow+"')");
pst = con.prepareStatement("INSERT INTO cregn (aplno, username, pwd, firstname,middlename,lastname, dob,gender, fathername, street,city,state, pincode, phone, email,occupation,secques,answer,dor) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pst.setInt(1, appno);
pst.setString(2, usname);
pst.setString(3, upwd);
pst.setString(4, fname);
pst.setString(5, mname);
pst.setString(6, lname);
pst.setString(7, dob);
pst.setString(8, gend);
pst.setString(9, faname);
pst.setString(10, saddr);
pst.setString(11, caddr);
pst.setString(12, staddr);
pst.setString(13, pin);
pst.setString(14, cno);
pst.setString(15, email);
pst.setString(16, occ);
// pst.setString(17,ph);
pst.setString(17, secques);
pst.setString(18, answer);
pst.setTimestamp(19, sqlNow);
pst.executeUpdate();
out.println("Registration Successful for application " + appno);
} catch (Exception ee) {
out.println("Invalid Data! All fields are mandatory..." + ee.getMessage());
}
%>
after executing this code error displayed "Invalid Data! All fields are mandatory..data truncation"
You are not executing the statement.
You need to call executeUpdate
You have to call execute or executeUpdate on pst in order to actually do the work. E.g., at the end:
pst.executeUpdate();
All that the code you've shown does is prepare the statement for execution, it doesn't execute it. This is one of the main differences between PreparedStatement and Statement. In Statement, you pass the SQL to execute directly into executeUpdate (as seen in your commented-out line using stmt). With a PreparedStatement, you supply the SQL with ? as you've done, set those parameters, and then call executeUpdate (or execute), which you haven't done.
There is no executeUpdate() being called on pst.
use pst.executeUpdate(); to execute the query and make sure that in transaction use setAutoCommit(true) has to be called.

Categories