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.
Related
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();
}
}
My Insert is failing via preparedStatment, I've run the statement through MySQL manually and it works, and I've double checked my params, but it's failing when run through the app.:
try {
myConn = DriverManager.getConnection(url, username, password);
preStmt = myConn.prepareStatement(
"Insert Into games(HomeTeamID, AwayTeamID, HomeTeamGoals, AwayTeamGoals, GameMonth, GameDay, GameYear, Overtime, Shootout)
Values(?, ?, ?, ?, '?', ?, ?, ?, ?);");
preStmt.setInt(1, game.getHomeID());
preStmt.setInt(2, game.getAwayID());
preStmt.setInt(3, game.getHomeGoals());
preStmt.setInt(4, game.getAwayGoals());
preStmt.setString(5, game.getGameMonth());
preStmt.setInt(6, game.getGameDay());
preStmt.setInt(7, game.getGameYear());
preStmt.setBoolean(8, game.isOvertime());
preStmt.setBoolean(9, game.isShootout());
preStmt.executeUpdate();
myConn.commit();
}
catch(SQLException sqlex) { // FAILING ON THIS CATCH
JOptionPane.showMessageDialog(null, "Error - Game Update Failed!\n\t-> SQL Error.");
}
I've scoured numerous docs online, but couldn't find any reason why it wouldn't work, and as mentioned, I run the same statement through MySQL with mock data, and it works...
Any suggestions?
Issue Resolved:
In values(), '?' doesn't fly, was just ?
I was passing comboBox.toString(), should have been passing comboBox.getSelectedItem().toString()
commit failed after as I'd not set myConn.setAutoCommit(false);, removed myConn.commit() and now works...
Thank you for directing to stackTrace, I'd been manually debugging and spaced on checking that :/ Sorry
I am writing a program that pulls data out of one schema, restructures the data to fit a new schema, and then inserts the data into a new database with the new schema. The problem is that, in my test code, the last record is not being inserted into the new database.
I am enclosing a greatly simplified version of the code below, which nonetheless recreates the problem. Can anyone show me how to fix the below so that all records in the recordset are inserted into the destination database? Currently, the below does correctly print out the last record in system.out.println, but yet that last record is not present in the destination table afterwards:
static void migrateDataTest(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_data_test");
Statement st = sourceConn.createStatement();
Connection destinationConn = DriverManager.getConnection("jdbc:odbc:receive_data_test");
int ClientNumber; String ClientsLastName; String ClientsFirstName;
ResultSet rest = st.executeQuery("SELECT ClientNumber, ClientsLastName, ClientsFirstName FROM sourceTable");
PreparedStatement ps5 = null;
while(rest.next()){
ClientNumber = rest.getInt(1);
ClientsLastName = rest.getString(2);
ClientsFirstName = rest.getString(3);
System.out.println(ClientNumber+", "+ClientsLastName+", "+ClientsFirstName);
ps5 = destinationConn.prepareStatement(
"INSERT INTO destinationTable ("
+ "ClientNumber, FirstName, LastName) VALUES (?, ?, ?)"
);
ps5.setInt(1, ClientNumber);
ps5.setString(2, ClientsFirstName);
ps5.setString(3, ClientsLastName);
ps5.executeUpdate();
destinationConn.commit();
}
ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
}
EDIT:
As per Lokesh's request, I am putting the entire code block which creates this error below. I just ran it again to confirm that it is printing record 30 in system.out.println, but that the destination table does not contain record number 30. The fact that the skipped record is printing out with system.out.println causes me to believe that the code below contains the error:
static void migrateDataTest(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_test");
Statement st = sourceConn.createStatement();
Connection destinationConn = DriverManager.getConnection("jdbc:odbc:receive_data_test");
int ClientNumber;
String ClientsLastName;
String ClientsFirstName;
String ClientsMiddleInitial;
Date DOB;
int GenderNumber;
int RaceNumber;
ResultSet rest = st.executeQuery("SELECT ClientNumber, ClientsLastName, ClientsFirstName, ClientsMiddleInitial, DOB, GenderNumber, RaceNumber FROM sourceTable");
PreparedStatement ps5 = null;
while(rest.next()){
ClientNumber = rest.getInt(1);
ClientsLastName = rest.getString(2);
ClientsFirstName = rest.getString(3);
ClientsMiddleInitial = rest.getString(4);
DOB = rest.getDate(5);
GenderNumber = rest.getInt(6);
RaceNumber = rest.getInt(7);
System.out.println(ClientNumber+", "+ClientsLastName+", "+ClientsFirstName+", "+ClientsMiddleInitial+", "+DOB+", "+GenderNumber+", "+RaceNumber);
ps5 = destinationConn.prepareStatement(
"INSERT INTO destinationTable ("
+ "ClientNumber, FirstName, MiddleInitial, LastName, DOB, GenderNumber, RaceNumber) "
+"VALUES (?, ?, ?, ?, ?, ?, ?)"
);
ps5.setInt(1, ClientNumber);
ps5.setString(2, ClientsFirstName);
ps5.setString(3, ClientsMiddleInitial);
ps5.setString(4, ClientsLastName);
ps5.setDate(5, DOB);
ps5.setInt(6, GenderNumber);
ps5.setInt(7, RaceNumber);
ps5.executeUpdate();
destinationConn.commit();
}
ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
}
The solution, oddly enough, was to create and execute an additional prepared statement after the one that was failing to insert the final value in its recordset. Once I added an additional prepared statement afterwards, the first one began to consistently insert all of its values.
Seems like some nuance in java code that perhaps is missing in the code samples that I posted in my original posting above.
I have a method which does a simple mysql insert, when I tried to rollback the insert action as follow, on an error but it is not rollingback on errors, please assist me,
public void addFamer(FamerDTO famer) throws Exception {
Connection con = JDBCConnectionPool.getInstance().checkOut();
con.setAutoCommit(false);
try {
String generalFamerDataSQL = "INSERT INTO famers(famer_code, name_wt_initials, full_name, gender, "
+ "nic_or_passport_no, sc_possition, phone_home, phone_mobile, phone_office) VALUES(?,?,?,?,?,?,?,?,?)";
PreparedStatement insertFamerPS = con.prepareStatement(generalFamerDataSQL, PreparedStatement.RETURN_GENERATED_KEYS);
insertFamerPS.setString(1, famer.getFamerCode());
insertFamerPS.setString(2, famer.getNameWithInitials());
insertFamerPS.setString(3, famer.getNameInFull());
insertFamerPS.setString(4, famer.getGender());
insertFamerPS.setString(5, famer.getNICorPassportNo());
insertFamerPS.setString(6, famer.getSocietyPosission());
insertFamerPS.setString(7, famer.getHomePhone());
insertFamerPS.setString(8, famer.getMobilePhone());
insertFamerPS.setString(9, famer.getOfficePhone());
insertFamerPS.execute();
String famerRelations = "INSERT INTO org_reg_blk_soc_fmr(org_id, region_id, famer_id, block_id, soc_id) "
+ "VALUES (?,?,?,?,?)";
PreparedStatement famerRelationsPS = con.prepareStatement(famerRelations);
famerRelationsPS.setInt(1, famer.getOrganization().getOrg_id());
famerRelationsPS.setInt(2, famer.getRegion().getRegion_id());
famerRelationsPS.setInt(3, famerID);
famerRelationsPS.setInt(4, famer.getBlock().getBlockId());
famerRelationsPS.setInt(6, famer.getSociety().getSoc_id()); //intentionally made an error here to test, put index as 6 for 5
famerRelationsPS.execute();
con.commit();
} catch (Exception e) {
if (con != null) {
logger.info("Rolling back!");
con.rollback();
}
logger.error(e.getLocalizedMessage());
} finally {
con.setAutoCommit(true);
JDBCConnectionPool.getInstance().checkIn(con);
}
}
once this method is called with the required parameters as there is a error in the second insert statement I expected to rollback the first insert action. but thought the error is shown, a record is added to the data base by the first insert statement.
Just to check - what is the table type you're using? Last time I used MySQL, MyISAM tables didn't support transactions, meaning you have to used another table type e.g. InnoDB.
I am trying to do an Insert, Update and Delete on a table in MS Access. Everything works fine
for a SELECT statement. But when doing the other three operations, I don't seem to get any
errors, but the actions are not reflected on to the DB. Please help...
THe INSERT statement is as follows:
PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1,1);
ps.setString(2,"ish");
ps.setInt(3,100);
ps.setInt(4,100);
ps.setInt(5,100);
ps.setInt(6,300);
ps.setInt(7,100);
ps.setString(8,"A");
ps.executeUpdate();
Also may I know why PreparedStatement is used except for SELECT statement...
I get this error:
Exception in thread "main" java.sql.SQLException: General error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6986)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3149)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedState
ment.java:216)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPrepare
dStatement.java:138)
at Student.main(Student.java:19)
This is my code...
import java.sql.*;
import java.io.*;
class Student {
public static void main(String args[]) throws SQLException, IOException, ClassNotFoundException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Student","","");
Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES (?, ?, ?, ?,
?, ?, ?, ?)");
ps.setInt(1,1);
ps.setString(2,"Girish");
ps.setInt(3,100);
ps.setInt(4,100);
ps.setInt(5,100);
ps.setInt(6,300);
ps.setInt(7,100);
ps.setString(8,"A");
ps.executeUpdate();
con.commit();
con.close();
}
}
This can happen when you don't commit/close the connection. Ensure that you're committing the connection after executing the statement and are closing the connection (and statement and resultset) in the finally block of the try block where they are been acquired and executed.
As to why the PreparedStatement is used, it's the common approach to avoid SQL injection attacks and to ease setting fullworthy Java objects like Date, InputStream, etc in a SQL query without the need to convert them to String.
I believe your prepared statement is of the wrong format. The documentation for INSERT INTO (available here: http://msdn.microsoft.com/en-us/library/bb208861(v=office.12).aspx) gives this format:
Single-record append query:
INSERT INTO target [(field1[, field2[, …]])] VALUES (value1[, value2[, …])
You give the format:
INSERT INTO target VALUES (value1[, value2[, …])
edit:
To be more clear I believe you want something like:
PreparedStatement ps = con.prepareStatement("INSERT INTO Student (Year, Name, field3 ...) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
Where Year, Name, field3 ... are the names of the fields you are trying to insert into.
The main reason for using a PreparedStatement is security. Generating a SQL query by concating strings is unsafe as the variable parts may contain SQL statements entered by a user. This would allow to execute statements like DROP TABLE * to the user (see SQL Injection). Theres is is a good idea only to use PreparedStatemnts if the SQL query is not static (doe snot contain variable parts).
Therefore it would be better also to use PreparedStatement for SELECT statements.
Edit :
You try to Insert your Student Primary Key, if it's an Identity column, it will not work.
You need to prepare your statement like this :
PreparedStatement ps = con.prepareStatement("INSERT INTO Student(Field1,Field2,Field3,Field4,Field5,Field6,Field7) VALUES (?, ?, ?, ?, ?, ?, ?)");
Without your Primary Key set, the DB will do it for you.
.
.
.
Original post :
There is a kind of similar question on StackOverflow.
You won't see any result from INSERT queries with Access until you close your Connection properly.
Your code doesn't close any resources, which will surely bring you grief. Call the close methods (in reverse order if there are more than one) in a finally block.
Here is a class DataBaseUtils to help you if needed.
public class DatabaseUtils
{
public static Connection createConnection(String driver, String url, String username, String password)
throws ClassNotFoundException, SQLException
{
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace(e);
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace(e);
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace(e);
}
}
}