insert skips last record in recordset - java

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.

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.

Insert database mysql get issue

i got issue when i go to Insert value to DB (do nothing).
before that i do select table to get last id, and it worked.
Here's my Code:
IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
Connection connection = null;
int idRoom = params.getInt("idRoom");
String betsmall = params.getUtfString("betsmall");
int Uid = params.getInt("recid");
try{
connection = dbManager.getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT id_game from detail_game ORDER BY id_game DESC LIMIT 1");
ResultSet res = stmt.executeQuery();
if (!res.first())
{
trace("bla bla");
}
int id = res.getInt("id_game");
trace (id);
// **till here there is no problem, i can get id from select query
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
stmts.setInt(1, Uid);
stmts.setInt(2, idRoom);
stmts.setInt(3, id);
stmts.setString(4, betsmall);
stmts.executeUpdate();
}
}
Here's the problem, insert do nothing.
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
Looks like you need some end parentheses in "VALUES".
A catch block to print stack trace would have told you the issue here as well. I'm not the best SQL guy, I always use this to check my SQL syntax as well to double check if I've done everything right.
your connection seems not auto commit. Try to add
stmts.commit();
after "stmts.executeUpdate();".

How do I send data from 4 text fields to a Derby Database in Netbeans using Java

I have a registration page where information for a customer can be entered into 4 text fields, i.e. Customer name, customer address, customer email and customer contact number.
I was wondering how to get the data from the text fields and into the Derby Database in netbeans using Java.
Well, you need to get the text from the fields first, so as follows:
//Replace the textfield names with your textfield variable names
String customerName = txtFieldCustomerName.getText();
String customerAddress = txtFieldCustomerAddress.getText();
String customerEmail = txtFieldCustomerEmail.getText();
String customerContactNumber = txtFieldCustomerContactNumber.getText();
Now that we have all the data, we can perform a database insert
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/myDB;create=true;user=me;password=mine");//Replace this with your information to your database
//now we have a connection, we can perform the insert
pstmt = con.prepareStatement("insert into TABLE_NAME_HERE (customerName, customerAddress, customerEmail, customerContactNumber) VALUES (?, ?, ?, ?)");
pstmt.prepareString(1, customerName);
pstmt.prepareString(2, customerAddress);
pstmt.prepareString(3, customerEmail);
pstmt.prepareString(4, customerContactNumber);
pstmt.executeUpdate(); //execute the insert
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally { //close the connection after everything is done.
try {
con.close();
pstmt.close();
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}

Insert declared variables into db Table using Java

So I am having a slight problem inserting values into a table I created in netbeans. I will show you the code that works and creates a new worker in the table and then show you what goes wrong when I try to change it.
This is a method from a class called dbConnect.java
public void insertTableRow() {
try {
Connection con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement();
String SQL = "INSERT INTO Workers VALUES (10, 'John', 'Smith', 'Engineer')";
stmt.executeUpdate(SQL);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
And is here where I call it in the main class.
dbConnect test = new dbConnect();
test.insertTableRow();
And then I get a John Smith appears so I know I have the right code. BUT when I try to enter in variables into VALUES it all falls apart. i.e.
public void insertTableRow(int id, String firstName, String lastName, String jobTitle) {
try {
int num = id;
String fName = firstName;
String lName = lastName;
String jTitle = jobTitle;
Connection con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement();
String SQL = "INSERT INTO Workers VALUES (num, fName, lName, jTitle)";
stmt.executeUpdate(SQL);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
Combined with -
dbConnect test = new dbConnect();
test.insertTableRow(10, "John", "Smith", "Doctor");
System.out.println(test.getTableContents());
The error I get back is:- Column 'NUM' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'NUM' is not a column in the target table.
So what am doing wrong because I have absolutely no idea?
when I try to enter in variables into VALUES it all falls apart
Statement stmt = con.createStatement();
String SQL = "INSERT INTO Workers VALUES (num, fName, lName, jTitle)";
stmt.executeUpdate(SQL);
You're not sending any variables. You have num, fName and the other variables but you're sending them as plain text in your SQL statement. You need to pass the values of your variables into your SQL statement.
The best approach to do this is using PreparedStatement:
String SQL = "INSERT INTO Workers VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(SQL);
p.setInt(1, num);
p.setString(2, fName);
p.setString(3, lName);
p.setString(4, jTitle);
pstmt.executeUpdate();
pstmt.close();
You may also use the naive approach of concatenating the values of each variable in your SQL statement, but it is unsafe and allows SQL Injection attacks. So the best bet is to use PreparedStatement.
More info:
Difference between Statement and PreparedStatement

my insert statement isn't working

am trying to insert values to the database but it seems there's a problem with the code if anyone can spot it. I am using a Servlet to get the user input and then sending the inputs to the following class using a method:
#Override
public String createItem(String title, String info, String url, String imageFilename) {
String addItem = title;
Connection conn = null;
try
{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + DBPath);
if (conn == null)
{
System.err.println("Database connection was null:(");
return addItem;
}
Statement stmt = conn.createStatement();
String query = "INSERT INTO items (title, info, URL, image) VALUES (newtitle, newInfo, newUrl, newImage )";
//String query = "INSERT INTO items (title, info, URL, image) VALUES(" + title + "," + info + "," + url +","+ imageFilename +")";
stmt.executeUpdate(query);
stmt.close();
}
catch(Exception e)
{
System.err.println("Exception querying database" + e.toString());
}
finally
{
try
{
conn.close();
}
catch(Exception e)
{
System.err.println("Exception querying database" + e.toString());
}
}
return addItem;
}
I have tried to type the values without using the values passed in the method from the servlet.
I have checked my insert Statement in the Sqlite Manager and its working, i also checked if the values were sent to the above class and it is working and i have tried the connection so it is enabling me to retrieve data from it but not inserting to it. so i have no idea why it is not storing the values in the DB.
This INSERT definitely isn't going to work:
String query = "INSERT INTO items (title, info, URL, image) VALUES (newtitle, newInfo, newUrl, newImage )";
Even if you wanted to store those as string literals, you'd have to use single quotes in the SQL statement like this:
String query = "INSERT INTO items (title, info, URL, image) VALUES ('newtitle', 'newInfo', 'newUrl', 'newImage' )";
To store the actual values instead of the variable names (which I'm guessing is what you want), use a PreparedStatement like this:
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO items (title, info, URL, image) VALUES (?, ?, ?, ?)"
);
stmt.setString(1, newtitle);
stmt.setString(2, newInfo);
stmt.setString(3, newUrl);
stmt.setString(4, newtitle);
stmt.executeUpdate();
Doing it this way prevents SQL injection attacks.

Categories