Insert JDateChoose into MySQL - java

I'm having a problem when I'm trying to Insert some Data into MySQL Database. I think it's caused because of the JDateChooser.
This is the error that I'm getting:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'May 24 21:06:17 CEST 2017, Fri May 26 00:00:00 CEST 2017, Desayuno, Adrian Poved' at line 1
And this is the method for insert the data:
public void nuevaReserva(ReservaVO reserva){
try {
Statement st = bd.getConexion().createStatement();
st.executeUpdate("INSERT INTO reserva VALUES(null,"+reserva.getInicio()+", "+reserva.getFin()
+", "+reserva.getRegimen()+", "+reserva.getCod_cliente()+", "+reserva.getCod_usuario()
+", "+reserva.getCod_habitacion()+");");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I also have this method in my controler to get the Data from the JDateChooser and from my ComboBoxes:
private void insertaReserva() {
ReservaDAO modeloReserva = new ReservaDAO();
String refEmpeladoS = String.valueOf(refEmpleado);
ReservaVO reserva = new ReservaVO("",nrv.getDateChooserLlegada().getDate().toString(),
nrv.getDateChooserSalida().getDate().toString(),
nrv.getListaPension().getSelectedItem().toString(),
nrv.getListaClientes().getSelectedItem().toString(),refEmpleadoS,
nrv.getListaHabitaciones().getSelectedItem().toString());
modeloReserva.nuevaReserva(reserva);
}
Thanks for help.

You need to use SimpleDateFormat.format() method to format the date to a string. You can't just use nrv.getDateChooserSalida().getDate().toString(), that gives you a data Object.
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
String dateFormatted = sdf.format(nrv.getDateChooserSalida().getDate().toString());
use DateFormatted,in the ReservaVO contructor.

Most likely you're missing quotes ' around your date value.
But that will only get you so far.
Some things to improve:
a) Use PreparedStatement / Bind Variables
Mainly this prevents nasty SQL injection into your database - and makes the SQL a bit better to read as well
public void nuevaReserva(ReservaVO reserva){
try {
PreparedStatement st = bd.getConexion().prepareStatement(
"INSERT INTO reserva VALUES(null, ?, ?, ?, ?, ?, ?)");
st.setString(1, reserva.getInicio());
st.setString(2, reserva.getFin());
st.setString(3, reserva.getRegimen());
st.setString(4, reserva.getCod_cliente());
st.setString(5, reserva.getCod_usuario());
st.setString(6, reserva.getCod_habitacion());
st.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Remember: I don't know about your column definitions. Might be some setInt() or else might be much better for your needs.
b) Improve by using try-with-resource
Your Databaseconnection bd.getConnexion() is never closed. That might be wanted (one connection open a long time) but in most systems I've seen that getConexion() of yours either opens a connection to the database (in which case you need to close it!) or takes one from a connection pool - in which case you want to return it ater use. Both can be done easily by using try-with-resource:
public void nuevaReserva(ReservaVO reserva){
try (Connection con = bd.getConexion();
PreparedStatement st = bd.getConexion().prepareStatement(
"INSERT INTO reserva VALUES(null, ?, ?, ?, ?, ?, ?)")) {
st.setString(1, reserva.getInicio());
st.setString(2, reserva.getFin());
st.setString(3, reserva.getRegimen());
st.setString(4, reserva.getCod_cliente());
st.setString(5, reserva.getCod_usuario());
st.setString(6, reserva.getCod_habitacion());
st.executeUpdate();
//Both statement and connection will be closed and closing curly brace
// even in case of an Exception!
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Insert into Oracle DB using Java

I am trying to insert values in a table on my oracle server, however, the program keeps running and doesn't execute. This is my code:
This is how I connect to the database:
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#abc.xxx.edu:1521:soeorcl","123",
"123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
Then I try to insert the values in the table:
try {
PreparedStatement prepareStatement = connection.prepareStatement("INSERT INTO MYTABLE (USERID, USERNAME, EMAILADDRESS, PHONENUMBER, PROFILEPICTURE )"
+ " VALUES (?, ?, ?, ?, ?)");
prepareStatement.setString(1, "10");
prepareStatement.setString(2, "ALI");
prepareStatement.setString(3, "gdgrgrregeg");
prepareStatement.setString(4, "0501977498");
prepareStatement.setNull(5, NULL);
prepareStatement.execute();
} catch (SQLException e) {
System.out.println("IT DOES NOT WORK");
}
The program gets stuck at prepareStatement.execute(); I have already checked the constraints and they work if I manually add them on the oracle server but the above code does not work.
Any ideas? Suggestions?
Try printing the sql string used in your prepared statement and then copy paste it and run it manually. Often times there are some misspellings or missing spaces in the string. In your case it could be an error from the way the statement is written.
I noticed that you need a space before VALUES.

Java prepared statement is not working?

I am writing a database program. But I am stuck with the Java prepared statement. The prepared statement doesn't seems to be working. I spend several hours to make it work but still same result.
String sql = "INSERT into EDMSDATABASE.MESSAGE (title, subject, description, deadline) VALUES (?, ?, ?, ?)";
try (
PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, bean.getTitle());
statement.setString(2, bean.getSubject());
statement.setString(3, bean.getDescription());
statement.setString(4, bean.getDeadline());
int affectedRow = statement.executeUpdate();
if(affectedRow == 1) return "Success";
} catch (SQLException e)
{
} finally{
}
Note that bean is a parameter
Are you using 1.7 . If not please use version compatible logic.

Mysql exception"out of range"?

I am working in swing based project and use prepared statement but it give exception like out of range and when i using parameters and do not put '?' but simply ? then show exception like"
jdbc syntax error check the manual near '?,?' at line one " i am so confused what is happening.Check my code what is wrong?
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
if (((JTextField) chose.getDateEditor().getUiComponent()).getText() == null) {
String sql = "INSERT INTO expance1 ( Breakfast,Date) VALUES (?,?)";
} else {
String sql = "INSERT INTO expance1 ( Breakfast,Date) VALUES (?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, breakfast.getText());
pst.setString(2, ((JTextField) chose.getDateEditor().getUiComponent()).getText());
pst.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "insert sucessfully");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try {
rs.close();
pst.close();
} catch (Exception e) {
}
}
}
}
Replace
pst.executeUpdate(sql);
by
pst.executeUpdate();
The SQL query has already been passed to the statement when preparing it. You must not pass it a second time. Passing it executes the literal SQL query, not the prepared one.

Inserting field values into database

I can't seem to figure out why I'm getting this exception: SQLException: Parameter index out of range (1 > number of parameters, which is 0). My mysql connector version is 5.1.29. Is this possible a problem with this version, or am I not properly setting up the query?
Scratch:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes"
+ "(bikename, country_of_origin, cost) VALUES"
+ "(?,?,?)";
try {
statement.setString(1, (String)winners_combo_box.getSelectedItem());
statement.setString(2, winner_fields[0].getText());
statement.setFloat(3, Float.parseFloat(winner_fields[1].getSelectedText()));
statement.executeUpdate(query);
} catch(SQLException e1) {
e1.printStackTrace();
}
}
You're not assigning a value to statement in that method, and you're using the overload of executeUpdate from Statement... rather than the parameterless one in PreparedStatement.
I suspect you actually want to assign the statement using Connection.prepareStatement:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes"
+ "(bikename, country_of_origin, cost) VALUES"
+ "(?,?,?)";
// TODO: Connection management?
PreparedStatement statement = conn.prepareStatement(query);
try {
statement.setString(1, (String)winners_combo_box.getSelectedItem());
statement.setString(2, winner_fields[0].getText());
statement.setFloat(3, Float.parseFloat(winner_fields[1].getSelectedText()));
statement.executeUpdate();
} catch(SQLException e1) {
e1.printStackTrace();
// TODO: Don't just pretend it worked...
} finally {
statement.close();
}
}
You shouldn't be trying to reuse a statement, basically. Personally I'd try not to reuse a connection, either, using connection pooling to handle reuse of the underlying connection, but that's a different matter.

Insert String type variables and a date type variable in MS access using java and sql INSERT Query

I posted a problem on how to convert string date to a date/time field to be added in access database: here is the Link
how to insert in a date/time ms access field using java sql INSERT query
I found a solution which i used here, here is my code
if(b==c.t.addR){
String n=Integer.toString(4);
String t=c.t.titlefield.getText();
String d=c.t.datefield.getText();
String p=c.t.progressfield.getText();
String pr=c.t.pselection;
String s="Open";
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try {
date = df.parse(d);
String query = "INSERT into Records (Deadline) Values(?)";
PreparedStatement ps = c.b.con.prepareStatement(query);
ps.setTimestamp(1,new java.sql.Timestamp(date.getTime()));
ps.executeUpdate();
}catch (Exception er) {
// TODO Auto-generated catch block
er.printStackTrace();
}
try {
c.b.st.executeUpdate("INSERT into Records (Title,Progress,Priority,Status) VALUES('"+t+"','"+p+"','"+pr+"','"+s+"') ");
JOptionPane.showMessageDialog(null, "Record Added");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
The problem now arise is that,, Date is added in a separate record while Other fields like title,progress etc are added in another!!!
How to INSERT date and other string fields in a single record.
Plz illustrate with some lines of code!!! Previous solution's modification will be very much helpful,, thanks!!
How to INSERT date and other string fields in a single record
make it a one insert statement rather than 2.
String query = "INSERT into Records (Deadline,Title,Progress,Priority,Status) Values(?,?,?,?)"
PreparedStatement ps = c.b.con.prepareStatement(query);
ps.setTimestamp(1,new java.sql.Timestamp(date.getTime()));
ps.setString(2,t);
ps.setString(3,p);
ps.setSring(4,pr);
ps.setString(5,s);
ps.executeUpdate();
You can insert int oa single record by executing one sql statement. You will just need to add the columns to the statement and set their values with the prepared statement. This is a more secure way of performing the insert instead of concatenating a String.
if(b==c.t.addR){
String n=Integer.toString(4);
String t=c.t.titlefield.getText();
String d=c.t.datefield.getText();
String p=c.t.progressfield.getText();
String pr=c.t.pselection;
String s="Open";
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try {
date = df.parse(d);
String query = "INSERT into Records (Deadline,Title,Progress,Priority,Status)"
+ "Values(?, ?, ?, ?,?)";
PreparedStatement ps = c.b.con.prepareStatement(query);
ps.setTimestamp(1,new java.sql.Timestamp(date.getTime()));
ps.setString(2,t);
ps.setString(3,p);
ps.setSring(4,pr);
ps.setString(5,s);
ps.executeUpdate();
}catch (Exception er) {
// TODO Auto-generated catch block
er.printStackTrace();
}
}

Categories