Kill Sybase processes using batch with java jdbc - java

I used Java to create a simple database process killer by sending a kill command in a loop. I want to know if I can use batch with kill command in one call:
try(Connection dbCon = GetDBConnection()){
try (Statement st = dbCon.createStatement();) {
dbCon.setAutoCommit(false);
for (int i = 0; i < processes.length; i++) {
st.addBatch("kill " + processes[i]);
}
st.executeBatch();
dbCon.commit();
dbCon.setAutoCommit(true);
}
catch (Exception e) {
System.out.println("Error SQL killing process: " + e);
}
catch (Exception e) {
System.out.println("Error opening connection: " + e);
}

I have the chance to try it and worked.
I have add some little changes to validate if it is only one process make a normal kill, and if it get more than one, then use batch.
try (Connection dbCon = GetDBConnection(); Statement st = dbCon.createStatement();) {
String queryKill = "kill ";
if (spids.length > 1) {
dbCon.setAutoCommit(false);
for (int i = 0; i < spids.length; i++) {
st.addBatch(queryKill + spids[i]);
System.out.println(queryKill + spids[i]);
}
st.executeBatch();
dbCon.commit();
dbCon.setAutoCommit(true);
} else {
queryKill = queryKill + spids[0];
System.out.println(queryKill + spids[0]);
st.execute(queryKill);
}
} catch (Exception e) {
killed = false;
System.out.println("Error SQL killing process: " + e);
}

Related

SQL executeUpdate() seems to commit data, but that is not the case. How can I find my error?

I curently work on few SQL queries (MSSQL 2O14), but only "SELECT" query works with executeQuery().
I had use execute() and executeUpdate() on "INSERT INTO" and "UPDATE" queries, but whereas it looks like working, no way.
FYI, in "UPDATE_PREVIOUS_H_LOT_STATUT,
int count= p.executeUpdate(); return 1. If h_lot_number is an unknown lot number, count = 0.
So, if I use wrong data in input, my query isn't executed(Until here, I agree) but when I use the expected data, the query is executed but there is no change in my DB.
How can I find where my error is ?
UPDATE Function :
public static boolean UPDATE_PREVIOUS_H_LOT_STATUT(String h_lot_number_old) {
try {
setUpConnexion("mainDB");
String baseQuery = "UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'";
//PreparedStatement p = newTransact("UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'", "mainDB");
PreparedStatement toReturn = (PreparedStatement) mainCon.prepareStatement(baseQuery);
int count = toReturn.executeUpdate();
if (count > 0) {
Log.d("Sucess : ", "Previous h_lot updated.");
closeCons();
return true;
} else {
Log.e("Error : ", "No lot found with this number.");
closeCons();
return false;
}
} catch (SQLException e) {
error = e.getMessage();
Log.e("Error :", error);
closeCons();
return false;
}
}
LOAD PREVIOUS NUMBER FUNCTION (works perfectly)
public static String LOAD_PREVIOUS_H_LOT_NUMBER(String machineNumber) {
String s = "";
try {
setUpConnexion("mainDB");
ResultSet RS = executeQuery("SELECT h_lot_number FROM valve_assembly_h WHERE machine_number = '" + machineNumber + "' AND statut = 'Actif'", "mainDB");
while (RS.next()) {
s = RS.getString(1);
Log.d("Success : ", "Lot number : " + s);
}
closeResultSet(RS);
} catch (Exception e) {
error = e.getMessage();
Log.e("Error :", error);
s = error;
}
closeCons();
return s;
}
Set up connection function : (works perfectly)
public static boolean setUpConnexion(String DBNAME) {
StrictMode.ThreadPolicy policy;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectURL;
try {
CONNECTION MS SQL SERVER
}
return true;
} catch (Exception e) {
System.out.println("SQL ERROR: " + e.getMessage());
e.printStackTrace();
return false;
}
}
Try to commit the transaction manually through the Connection object ,hope it helps.

JTextArea refreshment while SQL query running using java

I have a TextArea Object, and I have SQL query running, I have the GUI unusable until the SQL query is finished, I would like to get the GUI refreshed meanwhile.
Your SQL query is running on the Event Dispatch Thread (EDT) which is preventing the GUI from updating itself until the long running task is finished.
You need to run the query on a separate Thread.
An easy way to do this is to use a Swing Worker.
Read the section from the Swing tutorial on Concurrency for more information on the EDT and for examples of using a SwingWorker.
private String printCommandCalled(String argument) throws SQLException {
String finalResult = "";
url = url.substring(0, 15 + port.length() + adress.length()).concat(currentDatabaseName + "?useSSL=false");
try {
connection = (Connection) DriverManager.getConnection(url, userName, password);
statement = (Statement) connection.createStatement();
resultSet = (ResultSet) statement.executeQuery("SELECT * FROM " + argument + ";");
} catch (SQLException e) {
}
int i = resultSet.getMetaData().getColumnCount();
//this is the try block that takes too long resulting the unresponsiveness of the gui
try {
while (resultSet.next()) {
for (int j = 1; j <= i; j++)
finalResult += resultSet.getObject(j) + " ";
finalResult += '\n';
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int k = 1; k <= i; k++)
finalResult += resultSet.getMetaData().getColumnName(k) + " ("
+ resultSet.getMetaData().getColumnTypeName(k) + ") ";
finalResult += '\n';
//this output is a string that will be shown in the JTextArea object
return finalResult;
}

Ignore exception and continue to insert the rest of the data

I have the following codes snippet. I remove further details. I have a for loop with all the data in it. The I run the for loop for (int i = 0; i < list.getLength(); i++). What happens is that the moment any one of the data cause the sql with error say the data has a slash etc then it cause exception and the rest of the for loop cant continue. How can I like skip the one with the exception and continue with rest?
Here is a the codes.
Connection dbconn = null;
Statement stmt1 = null;
Statement stmt2 = null;
try
{
dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "tes1", "te15");
stmt1 = dbconn.createStatement();
stmt2 = dbconn.createStatement();
DateFormat outDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = Calendar.getInstance().getTime();
String value = null;
for (int i = 0; i < list.getLength(); i++)
{
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
}
}
catch (SQLException ex)
{
System.out.println("MyError Error SQL Exception : " + ex.toString());
}
catch (Exception rollback)
{
System.out.println("\nRollback :");
rollback.printStackTrace(System.out);
}
catch (Exception e)
{
System.out.println("\n Error here :");
e.printStackTrace(System.out);
}
finally
{
try
{
if (stmt1 != null)
{
stmt1.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt1 close");
ex.printStackTrace(System.out);
}
try
{
if (stmt2 != null)
{
stmt2.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt2 close");
ex.printStackTrace(System.out);
}
try
{
if (dbconn != null)
{
dbconn.close();
}
else
{
System.out.println("MyError: dbConn is null in finally close");
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for dbConn close");
ex.printStackTrace();
}
}
You need to put the try/catch block inside the for, around executeUpdate(insertCommand);
You need to catch the error in the loop too
....
for (int i = 0; i < list.getLength(); i++) {
try {
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
} catch (Exception e) {
// Better catch the real exception
// Handle the exception
}
}
....

CSV into MySQL Database

i have the following snippet:
String insertSql = "LOAD DATA INFILE 'C:/thomsonReuters/compressed/premium-world-check-day.csv'"
+ " INTO TABLE thomsenreuters.worldcheck "
+ " FIELDS TERMINATED BY '\t' "
+ " ENCLOSED BY '\"' "
+ " LINES TERMINATED BY '\r\n' "
+ " IGNORE 1 ROWS;";
This file has 4567 total rows. The fields are terminated by a tab and enclosed by double quotes. I try to insert the csv file by a Prepared-Update stmt. But Java only insert the first 4 rows into MySQL. What is the misstake i've done?
Thanks for help
EDIT
Full Class Code:
Connection con = null;
PreparedStatement stmt = null;
String truncateTable = "Truncate table thomsenreuters.worldcheck;";
String insertSql = "LOAD DATA INFILE 'C:/thomsonReuters/compressed/premium-world-check-day.csv'"
+ " INTO TABLE thomsenreuters.worldcheck "
+ " FIELDS TERMINATED BY '\t' "
+ " ENCLOSED BY '\"' "
+ " LINES TERMINATED BY '\r\n' "
+ " IGNORE 1 ROWS;";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Driver was found");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/thomsenreuters","XXXXXXX","XXXXXXX");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Connection to Database");
System.out.println("Start insert...");
try {
con.setAutoCommit(false);
stmt = con.prepareStatement(truncateTable);
stmt = con.prepareStatement(insertSql);
int total = stmt.executeUpdate();
con.commit();
con.setAutoCommit(true);
System.out.println("Total Rows insert " + total);
} catch (SQLException e) {
e.printStackTrace();
}
finally{
if(stmt != null)
{
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null)
{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Creating table with values in Java Derby

I am trying to create a table with values that are in a String array. I am looking for the best way to loop through it without having to send a bunch of queries. This is what I have but obviously the loop wont work. Anyone have a better way of performing this?
public static void createTable(String table, String[] values) throws SQLException{
try {
Class.forName(driver);
conn = DriverManager.getConnection(connectionURL);
Statement state = conn.createStatement();
for(int x = 0; x < values.length; x++){
state.execute("CREATE TABLE" + table + " ( " + values[x] + " );");
}
conn.commit();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Concatenate the elements of Values array.
StringBuilder sb=new StringBuilder();
sb.append("CREATE TABLE " + table + " ( ");
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i >= values.length-1) {break;}
sb.append(",");
}
sb.append(" )");
state.execute(sb.toString());

Categories