Inserting information from one mysql table to another - java

I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}

You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.

I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.

With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;

Related

MySQL checking if something is already in a column

I am new to MySQL and don't really know how to check if in the column "friendCode" the same value already exist and if that's the case it should look if in the same row in the "watched" column the value "0" is. I have already managed to check whether the code exists in a row. I just don't know how to look for the second condition.
Here is a picture how the table looks like:
And here that what I already managed to do:
public static boolean checkRow(String query) {
boolean ret = false;
try (Connection con = DriverManager.getConnection(url, user, password)) {
Statement stmt = con.createStatement();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next() && !rs.getString("watched").equals(0)) {
ret = false;
} else {
ret = true;
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return ret;
}
I think you are not written any select query in this program. If you are calling from the main method just check and try the below steps.
In Given Table watched column have integer DataType data.
Your Compare to String type.
Try it my code it's working if you have any concern revert back to this comment.
public static boolean checkRow(String query) {
boolean ret = false;
try (Connection con = DriverManager.getConnection(url, user, password)) {
Statement stmt = con.createStatement();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next() && rs.getString("watched")!=0) {
ret = false;
} else {
ret = true;
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return ret;
}

How to update one object variable on a SQL database?

I have it set up where I can save my object information to a SQL database using this block of code:
public boolean add(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if (aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
sqlStr.append("INSERT INTO ");
sqlStr.append(ORDER_TABLE);
sqlStr.append(" (firstName, lastName, size, cheese, sausage, ham, total)");
sqlStr.append(" VALUES (?,?,?,?,?,?,?)");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString(), Statement.RETURN_GENERATED_KEYS);
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
if (rowCount == 1) {
ResultSet rs = statement.getGeneratedKeys();
if(rs.next()) {
aOrder.setId(rs.getInt(1));
}
success = true;
}
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot save pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Insert", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
What I am trying to do is change the total variable with an update to the object on the server. I dont have an error right now popping up but nothing is changing in my objects information. Here is my code with the update block:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
//TODO create the SQL and prepared statements to update an order in the database
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET firstName = ?, lastName = ?, size = ?, cheese = ?, sausage = ?, ham = ?, total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I have it set up that just the total variable will be changed by the time the update block of code will be ran. So I was trying to just call all the variables again in the hopes that it would change the total.
I get the same results with this update block of code:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I figured out my problem I had something elsewhere in my code blocking the update. This is the code that is working to update the mySQL database in this case:
try {
//TODO create the SQL and prepared statements to update an order in the database
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ?");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
statement.setInt(2, aOrder.getId());
rowCount = statement.executeUpdate();
}

checking duplicate for more than two values, if no such duplicate then insert query

Note:
I have two columns (Name(primary key), Email(primary key))
I have inserted two rows.
The 1st row, where name=ema email=ema#gmail.com, and my 2nd row where name=ena email=fe.
Now, when I want to insert a new record it only checks with the 1st row and the checking works, but if I want to insert name=ena and email=something it does not check for the second row. Can someone please suggest to me how do I overcome this?
try
{
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//block of code to check user exists or not.
//Statement statement = connection.createStatement();
PreparedStatement Pstatement;
String query = "select Name,Email from detail";
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery() ;
if(rs.next())
{
//from database
String name_db1 = rs.getString("Name").trim(); //using trim removes all white spaces
String email_db2 = rs.getString("Email").trim();
//from user GUI
String entered_name = name.getText().trim(); //using trim removes all white spaces
String entered_email = email.getText().trim();
boolean valid = true;
if(entered_name.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter name");
valid = false;
}
else if(name_db1.equals(entered_name))
{
JOptionPane.showMessageDialog(null,"Enter name taken");
name.setText(null);
valid = false;
}
else if(entered_email.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter email");
valid = false;
}
else if(email_db2.equals(entered_email))
{
JOptionPane.showMessageDialog(null,"email taken");
email.setText(null);
valid = false;
}
else if(valid == true)
{
Pstatement=connection.prepareStatement("insert into detail values(?,?)");
//Specifying the values of preparestatement parameter
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"registration successful");
//x++;
}
}
else
{
//incase if the user click without filling up the fields
JOptionPane.showMessageDialog(null,"not yet registered");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Finally, I have figured out the logic, I just need to create a separate query for both Name and Email. This way I can search more than two values :D. If there is any mistake please let me know.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//creating a query for Name
String query1 = "select Name, Email from detail where Name like '"+name.getText()+"'";
PreparedStatement statement1 = con.prepareStatement(query1);
//creating a query for Email
String query2 = "select Name, Email from detail where Email like '"+email.getText()+"'";
PreparedStatement statement2 = con.prepareStatement(query2);
ResultSet result1 = statement1.executeQuery(); //resultset for name
ResultSet result2 = statement2.executeQuery(); //resultset for email
//checking name exception
if (result1.next())
{
String dbasename=result1.getString("Name").toString().trim();
String enteredname=new String(name.getText().trim());
if(enteredname.equals(""))
{
JOptionPane.showMessageDialog(null, "enter name");//valid1 = false;
}
else if(dbasename.equals(enteredname))
{
JOptionPane.showMessageDialog(null, "name taken");//valid1 = false;
name.setText(null);
}
}
//checking email exception
else if(result2.next())
{
String dbaseemail=result2.getString("Email").toString().trim();
String enteredemail=new String(email.getText().trim());
if(enteredemail.equals(""))
{
JOptionPane.showMessageDialog(null, "enter email");//valid1 = false;
}
else if(dbaseemail.equals(enteredemail))
{
JOptionPane.showMessageDialog(null, "email taken");//valid1 = false;
email.setText(null);
}
}
//if no exception is detect exectute the below statement
else
{
PreparedStatement Pstatement=con.prepareStatement("insert into detail values(?,?)");
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"Registered Successfully");
}
statement1.close();
statement2.close();
con.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error during searching");
}

Java JDBC display first 500 records at a time, commit, than display the next 500 records and etc

So I want to be able to display 500 records at a time, commit and print that it has been displayed records 1 to 500 records have been committed. And than do the next 500 records and commit again until reached the maximum records which is over 20k records. I managed to get the first 500 records but I am stuck how can I commit them and in commit them and continue to get the next 500 records and so on.
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE"
+ " WHERE profile_id >= ? AND profile_id <= ?;";
try {
dbConnection = getInformixConnection(); //connects to ICORE database
System.out.println("I am in the try");
//Gets the max profile_id record
statement = dbConnection.createStatement();
ResultSet r = statement.executeQuery("SELECT max(profile_id) AS rowcount FROM COS_PROFILE");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("COS_PROFILE table before update has " + maxCount + " row(s).");
preparedStatement = dbConnection.prepareStatement(selectTableSQL);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, maxCount);
// execute select SQL statement
rs = preparedStatement.executeQuery();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database ICORE Connection is closed");
}
}
}
private static void updateRecordIntoBids() throws SQLException {
System.out.println("I am inside update method");
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
dbConnection = getOracleConnection(); //connects to BIDS database
String updateTableSQL =
"UPDATE traffic_profile_temp SET pe_ingress_flag = ?, "
+ " pe_egress_flag = ?,"
+ " ce_ingress_flag = ?,"
+ " ce_egress_flag = ? "
+ " WHERE traffic_profile_id = ? ";
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
try {
int rowCount = 0;
while (rs.next() && rowCount < 500) {
// System.out.println("inside the while loop");
String ingressflag = rs.getString("ingress_flag"); //BIDS column is pe_ingress_flag
String egressflag = rs.getString("egress_flag"); //BIDS column is pe_egress_flag
String ceingressflag = rs.getString("ce_ingress_flag"); //BIDS column is ce_ingress_flag
String ceegressflag = rs.getString("ce_egress_flag"); //BIDS column is ce_egress_flag
int profileid = rs.getInt("profile_id"); //BIDS column is traffic_profile_id
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setInt(5, profileid);
// System.out.println(updateTableSQL);
System.out.println("Record " +profileid +" is updated to traffic_profile_temp table!");
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
System.out.println(rowCount);
}
preparedStatement.executeBatch();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database BIDS Connection is closed");
}
}
}
update this part
while (rs.next() && rowCount < 500) {
with
while (rs.next()) {
and
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
System.out.println(rowCount);
with
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
if(rowCount % 500 == 0){
preparedStatement.executeBatch();
}
System.out.println(rowCount);
This check if the rowCount can be divided by 500, execute the batch. Don't forget to execute the batch after all statements finish to execute the remaining batches which couldn't divided by 500 . for more details regarding batches

how to check database table is empty or not

i have a database with a table 'admin'.But presently just creating table not having any values.table columns are user_name and password.My motive is to check whether the table is empty or not.I am using mysql database.I tried following code and its fails.Please help me.
public void nullCheck() {
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT * From admin ";
try {
stmt = (PreparedStatement) conn.prepareStatement(qry);
rs = stmt.executeQuery();
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
Util.showWarningMessageDialog("null");
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you just need to check the table then you should use query:
String qry = "SELECT count(*) From admin ";
for better performance.
And get the row count from ResultSet to check the table is null or not.
int count=0;
while( rs.next() )
{
count=rs.getInt("count");
}
Try this code, I think this will do it. I updated it coz the first I post here is not working at all, my bad.
public void nullCheck() {
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT * From admin ";
try {
stmt = (PreparedStatement) conn.prepareStatement(qry);
rs = stmt.executeQuery();
int count = 0;
while(rs.next()){
count++;
}
if(count == 0){ // if equal to 0 then the table is null
bla bla bla
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}

Categories

Resources