Related
I'm working with Teamcenter and Catia via the Java SOA libraries. I'm running into an issue where the demo code appears broken and I can't find a good example or documentation to work towards. The following code results in a null value exception. Specifically the line "session = PortalContext.getContext().getSession();" is where I'm crashing.
package com.ebsolutions.catiman.actions;
import java.io.File;
import java.io.RandomAccessFile;
/*
* Tc java classes
*/
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentRevisionRuleType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
/*
* Catia integration java classes
*/
import com.ebsolutions.catiman.ErrorWarningMessages;
import com.ebsolutions.catiman.PortalContext;
import com.ebsolutions.catiman.commands.TClassUserLUSCommand;
/**
* Sample file.
* This class is not launched by the CATIAV5 integration
*
* #date 02/06/2008
*/
public class SampleIndependentSilentLUS
{
/**
* Current TC session: needed to access Tc server (service.call)
* null value is not allowed.
*/
protected TCSession session = null;
/**
* This flag defines wether the LUS should be performed in silent mode or not
*/
protected boolean is_silent[];
/**
* title of the messages
*/
private String _title = "Sample Independent SilentLUS";
/**
* components that contains the assembly to LUS.
*/
private TCComponentItem[] item = null;
private TCComponentItemRevision[] item_revision = null;
private TCComponentDataset[] part_dataset = null;
private TCComponentDataset[] product_dataset = null;
private TCComponentDataset[] drawing_dataset = null;
private TCComponentForm[] other = null;
private TCComponentBOMWindow bom_window[] = null;
/**
* The constructor.
*/
public SampleIndependentSilentLUS()
{
/* try to find the TCSession
note: this is not the only way to retrieve the TCSession. */
session = PortalContext.getContext().getSession();
}
/* --------------------------------------------------------------------- */
/*
* Sample main function
* #date 02/06/2008
*/
public void customerProcess() {
showInformationMessage("START of silent LUS");
TClassUserLUSCommand silent_lus_command = null;
/*
* example of searching items to LUS
*/
int return_value = findItemToLUS();
if (return_value < 0)
{
/* Unable to find any item to LUS */
return;
}
/**
* Initialize the API
*/
silent_lus_command = new TClassUserLUSCommand(session);
/*
* API: LUS process.
* call the "executeLUS" function
*/
/******* Item ********/
try
{
if (item[0] != null)
{
silent_lus_command.executeLUS(item[0], is_silent[0]);
showInformationMessage("pause in silent LUS after Item");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (1) Exception : " + ex);
}
/******* Item Revision ********/
try
{
if (item_revision[1] != null)
{
silent_lus_command.executeLUS(item_revision[1], is_silent[1]);
showInformationMessage("pause in silent LUS after Item_rev");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (2) Exception : " + ex);
}
/******* bom window ********/
try
{
if (bom_window[2] != null)
{
silent_lus_command.executeLUS(bom_window[2], is_silent[2]);
showInformationMessage("pause in silent LUS after bom_widow");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (3) Exception : " + ex);
}
/******* CATPart dataset ********/
try
{
if (part_dataset[3] != null)
{
silent_lus_command.executeLUS(part_dataset[3], is_silent[3]);
showInformationMessage("pause in silent LUS after CATPart");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (4) Exception : " + ex);
}
/******* CATProduct dataset ********/
try
{
if (product_dataset[4] != null)
{
silent_lus_command.executeLUS(product_dataset[4], is_silent[4]);
showInformationMessage("pause in silent LUS after CATProduct");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (5) Exception : " + ex);
}
/******* CATDrawing dataset ********/
try
{
if (drawing_dataset[5] != null)
{
silent_lus_command.executeLUS(drawing_dataset[5], is_silent[5]);
showInformationMessage("pause in silent LUS after CATDrawing");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (6) Exception : " + ex);
}
/******* other dataset ********/
try
{
if (other[6] != null)
{
silent_lus_command.executeLUS(other[6], is_silent[6]);
showInformationMessage("pause in silent LUS ");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (7) Exception : " + ex);
}
silent_lus_command.stopProcess();
}
/**
* is used to display an Error message
* #param i_msg (I) the message to be displayed
*/
private void showErrorMessage(final String i_msg)
{
ErrorWarningMessages.showErrorMessage(i_msg, _title);
}
/**
* is used to display an Information message
* #param i_msg (I) the message to display
*/
private void showInformationMessage(final String i_msg)
{
ErrorWarningMessages.showInformationMessage(i_msg, _title);
}
/**
* Sample of searching item to LUS.
* read the query.txt file that contains the item_id, item_rev_id and silent mode of the selected item
* The first line contains the number of assembly to LUS
* Then, for each assembly, we need 3 lines : item_id, item_rev_id and silent_mode
* example :
* 2
* 000010
* A
* true
* 000020
* B
* false
*/
protected int findItemToLUS()
{
String item_id = null;
String item_rev_id = null;
int return_value = 0;
int nb_assy = 0;
RandomAccessFile reader = null;
File file = null;
try
{
String file_path = "c:\\catiman_tmp\\tmp\\query.txt";
file = new File(file_path);
reader = new RandomAccessFile(file, "r");
nb_assy = Integer.valueOf(reader.readLine()).intValue();
is_silent = new boolean[nb_assy];
item = new TCComponentItem[nb_assy];
item_revision = new TCComponentItemRevision[nb_assy];
part_dataset = new TCComponentDataset[nb_assy];
product_dataset = new TCComponentDataset[nb_assy];
drawing_dataset = new TCComponentDataset[nb_assy];
other = new TCComponentForm[nb_assy];
bom_window = new TCComponentBOMWindow[nb_assy];
}
catch (Exception ex)
{
showErrorMessage("error 0 - " + ex);
return_value = -1;
}
for (int i = 0 ; i < (nb_assy) ; i++)
{
try
{
item_id = reader.readLine();
item_rev_id = reader.readLine();
is_silent[i] = Boolean.valueOf(reader.readLine()).booleanValue();
// search item name item_id
TCComponentItemType it = (TCComponentItemType)(session.getTypeComponent("Item"));
item[i] = it.find(item_id);
if (item[i] == null)
{
showErrorMessage("Error : item <" + item_id + ">not found");
return_value = -1;
}
else
{
// the item was found, search the correction item revision
AIFComponentContext[] revisions = item[i].getChildren();
TCComponentItemRevision revision_component = null;
for (int j = 0; j < revisions.length; j++)
{
InterfaceAIFComponent component = revisions[j].getComponent();
if (component instanceof TCComponentItemRevision)
{
revision_component = (TCComponentItemRevision) component;
if (revision_component.getProperty("item_revision_id").equals(item_rev_id))
{
item_revision[i] = revision_component;
break;
}
}
}
if (item_revision[i] == null)
{
showErrorMessage("Error : Item revision [" + item_rev_id + "] doesn't exist for item [" + item_id + "]");
return_value = -1;
}
else
{
// create the BOMWindow with the item revision previously found
TCComponentBOMWindowType type = (TCComponentBOMWindowType)session.getTypeComponent("BOMWindow");
TCComponentRevisionRuleType rule = (TCComponentRevisionRuleType)session.getTypeComponent("RevisionRule");
bom_window[i] = type.create(rule.getDefaultRule());
/* Define the BOMWindow top line */
TCComponentBOMLine top_line = bom_window[i].setWindowTopLine(item[i], item_revision[i], null, null);
}
}
}
catch (Exception ex)
{
showErrorMessage("error 1 - " + ex);
return_value = -1;
}
// search for a dataset (CATPart or CATProduct and/or CATDrawing)
try
{
int nb = item_revision[i].getChildrenCount();
if (nb > 0)
{
AIFComponentContext[] aif_comp_cont = item_revision[i].getChildren();
for (int j = 0 ; j < nb ; j++)
{
InterfaceAIFComponent int_aif_comp = aif_comp_cont[j].getComponent();
if (int_aif_comp.getType().equals("CATPart"))
{
part_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATProduct"))
{
product_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATDrawing"))
{
drawing_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("ItemRevision Master"))
{
other[i] = (TCComponentForm)int_aif_comp;
}
}
}
}
catch (Exception ex)
{
showErrorMessage("error 2 - " + ex);
return_value = -1;
}
}
try
{
reader.close();
}
catch (Exception ex)
{
showErrorMessage("error 3 - " + ex);
}
return return_value;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Lets try this");
SampleIndependentSilentLUS test = new SampleIndependentSilentLUS();
//test.customerProcess();
}
}
There are two ways to get TCSession.
1) If you writing a Rich-Client Plugin
//numTry - number of attemts
private static TCSession getCurrentSession(int numTry) throws Exception {
try {
TCSession session = null;
ISessionService iss=null;
int numtry=numTry;
while (iss==null && numtry>0) {
iss = AifrcpPlugin.getSessionService();
numtry--;
}
session=(TCSession)iss.getSession("com.teamcenter.rac.kernel.TCSession");
return session;
}
catch (Exception ex) {
throw ex;
}
}
2) If you writing a stand-alone application, using SOA to work with Teamcenter API.
In this case, you need to connect teamcenter first. View "HelloTeamcenter" example in documentation for details.
did you get a solution for this?
SampleIndependentSilentLUS is a very good way of automating LUS process.but i prefer using the other class(SampleSilentLUS ) that can be called from command line because TCIC will automatically provide a TCSession
the session object you get from SOA(com.teamcenter.services.strong.core._2008_06.Session) is not compatible with RAC Session(com.teamcenter.rac.TCSession).
but if you use loose services(com.teamcenter.services.loose.core), i think you can simply typecast to TCSession
I am implementing a Java Client-Server application for a university task and I'm stuck at the following point: I am obliged to use client-server and also update the view whenever the data in the database changes. What I have done is that whenever a change in the database should occur I notify all the clients with the "CHANGE IN DATA" message and then the client should read and understand this message in order to call a method that will update it's graphic interface. However, or I'm mistaking the reading part on client side or because of some error, the clients don't read the "CHANGE IN DATA" message so the whole gets stuck at this point and the view doesn't update.
Here are some relevant codes!
Server class:
public class FinesPaymentServer implements Runnable {
private Database database;
private UserGateway userGateway;
private FineGateway fineGateway;
private DriverGateway driverGateway;
private Socket connection;
private int ID;
static ArrayList<Socket> clientsConnected;
/**
* Constructor of the class connecting to the database and initializing the socket
* #param database the database used
* #param connection the socket for the server
* #param ID the id
*/
private FinesPaymentServer(Database database, UserGateway userGateway, FineGateway fineGateway, DriverGateway driverGateway, Socket connection, int ID) {
this.connection = connection;
this.userGateway = userGateway;
this.fineGateway = fineGateway;
this.driverGateway = driverGateway;
this.database = database;
this.ID = ID;
}
/**
* Run method of the threads for each socket on the server
*/
public void run() {
try {
while(true)
readFromClient(connection);
} catch (IOException | SQLException e) {
System.out.println(e);
}
}
/**
* Read method from the client
* #param client the client socket from where to read
* #throws IOException
* #throws SQLException
*/
public void readFromClient(Socket client) throws IOException, SQLException {
BufferedInputStream is = new BufferedInputStream(client.getInputStream());
InputStreamReader reader = new InputStreamReader(is);
StringBuffer process = new StringBuffer();
int character;
while((character = reader.read()) != 13) {
process.append((char)character);
}
System.out.println("[SERVER READ]: "+process);
String[] words = process.toString().split("\\s+");
switch (process.charAt(0)) {
case 'a' :
{
int type = database.verifyLogin(words[1], words[2]);
sendMessage(client, ""+type + " ");
break;
}
case 'b' :
{
String rs = userGateway.getUsers();
sendMessage(client, rs);
break;
}
case 'c' :
{
userGateway.createUser(words[1], words[2], words[3]);
notifyClients();
break;
}
case 'd' :
{
userGateway.updateUser(words[1], words[2], words[3]);
notifyClients();
break;
}
case 'e' :
{
userGateway.deleteUser(words[1]);
notifyClients();
break;
}
}
try {
Thread.sleep(1000);
} catch (Exception e){}
String time_stamp = new java.util.Date().toString();
String returnCode = "Single Socket Server responded at " + time_stamp + (char) 13;
sendMessage(client, returnCode);
}
/**
* Method for sending messages from the server to the client
* #param client the client socket where to send the message
* #param message the message itself to be sent
* #throws IOException
*/
private void sendMessage(Socket client, String message) throws IOException {
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
System.out.println("[SERVER WRITE]: "+message);
writer.flush();
}
public void notifyClients() throws IOException
{
for(Socket s : clientsConnected)
{
sendMessage(s, "CHANGE IN DATA ");
}
}
/**
* #param args the command line arguments
* #throws java.sql.SQLException
*/
public static void main(String[] args) throws SQLException {
Database database = new Database();
UserGateway userGateway = new UserGateway();
FineGateway fineGateway = new FineGateway();
DriverGateway driverGateway = new DriverGateway();
clientsConnected = new ArrayList<>();
// Setting a default port number.
int portNumber = 2015;
int count = 0;
System.out.println("Starting the multiple socket server at port: " + portNumber);
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
System.out.println("Multiple Socket Server Initialized");
//Listen for clients
while(true) {
Socket client = serverSocket.accept();
clientsConnected.add(client);
Runnable runnable = new FinesPaymentServer(database, userGateway, fineGateway, driverGateway, client, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
} catch (Exception e) {}
}
}
The client class:
public class FinesPaymentClient implements Runnable {
private String hostname = "localhost";
private int port = 2015;
Socket socketClient;
AdministratorModel adminModel;
PoliceModel policeModel;
PostModel postModel;
/**
* Constructor of the class
* #param hostname the host name of the connection
* #param port the port of the connection
* #throws UnknownHostException
* #throws IOException
*/
public FinesPaymentClient(String hostname, int port, AdministratorModel adminModel, PoliceModel policeModel, PostModel postModel) throws UnknownHostException, IOException
{
this.hostname = hostname;
this.port = port;
this.adminModel = adminModel;
this.policeModel = policeModel;
this.postModel = postModel;
connect();
}
/**
* Method for connecting to the host by a socket
* #throws UnknownHostException
* #throws IOException
*/
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("Connection Established");
}
/**
* Method for reading response from the server
* #return the string read from the server
* #throws IOException
*/
public String readResponse() throws IOException {
String userInput;
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(socketClient.getInputStream()));
System.out.println("[CLIENT READ]:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
return userInput;
}
return userInput;
}
/**
* Method for closing connection between client and server
* #throws IOException
*/
public void closeConnection() throws IOException {
socketClient.close();
}
/**
* Method for writing messages to the server
* #param message the message to be sent
* #throws IOException
*/
public void writeMessage(String message) throws IOException {
String time_stamp = new java.util.Date().toString();
// Please note that we placed a char(13) at the end of process...
// we use this to let the server know we are at the end
// of the data we are sending
String process = message + (char) 13;
BufferedWriter stdOut = new BufferedWriter(
new OutputStreamWriter(socketClient.getOutputStream()));
stdOut.write(process);
System.out.println("[CLIENT WRITE]: "+process);
// We need to flush the buffer to ensure that the data will be written
// across the socket in a timely manner
stdOut.flush();
}
#Override
public void run() {
try {
String response;
while(true)
{
response = readResponse();
System.out.println("HERE"+response.substring(0, 13));
if(response.substring(0, 13).equals("CHANGE IN DATA"))
{
adminModel.setChange();
}
}
} catch (IOException e) {
System.out.println(e);
}
}
/**
* Main method of the application
* #param arg the parameters given as arguments
* #throws SQLException
* #throws UnknownHostException
* #throws IOException
*/
public static void main(String arg[]) throws SQLException, UnknownHostException, IOException {
AdministratorModel adminModel = new AdministratorModel();
PoliceModel policeModel = new PoliceModel();
PostModel postModel = new PostModel();
FinesPaymentClient client = new FinesPaymentClient("localhost", 2015, adminModel, policeModel, postModel);
Runnable client2 = new FinesPaymentClient("localhost", 2015, adminModel, policeModel, postModel);
Thread thread = new Thread(client2);
thread.start();
Login login = new Login();
ClientSide clientSide = new ClientSide(login, client, adminModel, policeModel, postModel);
}
}
ClientSide class:
public class ClientSide {
private final Login login;
private FinesPaymentClient client;
AdministratorModel adminModel;
PoliceModel policeModel;
PostModel postModel;
/**
* Constructor instantiating needed classes
* #param login an instance of the login class
* #param client the client needing the control logic
* #param adminModel
* #param policeModel
* #param postModel
* #throws SQLException using classes connecting to a database sql exceptions can occur
*/
public ClientSide(Login login, FinesPaymentClient client, AdministratorModel adminModel, PoliceModel policeModel, PostModel postModel) throws SQLException
{
this.login = login;
this.client = client;
this.adminModel = adminModel;
this.policeModel = policeModel;
this.postModel = postModel;
login.addButtonListener(new ButtonListener());
}
/**
* Listener for the login button. Reads, verifies and provides the interface according to logged in user type.
*/
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try
{
client.writeMessage("a " + login.field1.getText()+ " " + login.field2.getText());
String response = client.readResponse();
if(response.charAt(0) == '1')
{
login.setVisible(false);
AdministratorGUI administratorGUI = new AdministratorGUI(adminModel, client);
AdministratorController adminController = new AdministratorController(client, administratorGUI, adminModel);
}
//if user is post office employee
else if(response.charAt(0) == '2')
{
login.setVisible(false);
PostGUI postGUI = new PostGUI();
PostController postController = new PostController(client, postGUI, postModel);
}
//if user is police employee
else if(response.charAt(0) == '3')
{
login.setVisible(false);
PoliceGUI policeGUI = new PoliceGUI();
PoliceController policeController = new PoliceController(client, policeGUI, policeModel);
}
else
{
JOptionPane.showMessageDialog(null,"Login failed! Please try again!");
}
}
catch (IOException ex)
{
Logger.getLogger(ClientSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I'm 99% sure that the error is on client side reading the message sent from the server as notification, but I simply cannot figure it out how could I retrieve that message. Right now I have a try in the client threads run method, but doesn't work. Other classes and other functionalities work just fine, this is my only problem. Do you have any ideas what the mistake could be? I would appreciate any help.
I try to read CSV files into a MySQL-DB but the files have more than 40000 lines. The CSV-Reader is not the problem. And I can write the lines into the MySQL-DB. But when I will read and write all lines of the CSV my Connection to the MySQL-Server gets killed in the process. The Program reads and writes successfully more than 1000 lines before my connection ends. I get the following errors:
java.sql.SQLException: Could not retrieve transation read-only status server
Or
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 328.971 milliseconds ago. The last packet sent successfully to the server was 328.971 milliseconds ago.
Do you have any idea why this is?
I wrote in the catch-block a method that renews the connection but it read few rows and the connection was kill again.
The Code to get the lines from the CSV and load into the MySQL-DB
kptoolsDB.setAutoCommit(false);
dateiImpDB.setAutoCommit(false);
while(prop != null && this.isInterrupted() == false)
{
vertragsID = null;
rufNr = null;
try {
setDaten(prop);
kptoolsDB.commit();
dateiImpDB.commit();
} catch (SQLException e) {
e.printStackTrace();
log.log(LogLevel.ERROR, e.toString(), this);
setDBConnections(hilfstabelle);
try {
setDaten(prop);
kptoolsDB.commit();
dateiImpDB.commit();
} catch (SQLException e1) {
log.log(LogLevel.ERROR, e.toString(), this);
setDBConnections(hilfstabelle);
}
}
view.setProgessBarVal(count);
prop = reader.getNextLine();
count++;
}
kptoolsDB.setAutoCommit(true);
dateiImpDB.setAutoCommit(true);
The method setDaten()
private void setDaten(Properties prop) throws SQLException
{
ResultSet rst;
rst = statKPTools.executeQuery("select rechnungsID from isimrechnungeintrag where rawcdr = " + prop.get("i_rawcdr") + ";");
if(rst.next())
{
log.log(LogLevel.INFO, "Die CDR-Nummer " + prop.get("i_rawcdr") + " ist schon eingetragen!", this);
} else {
rst.close();
rufNr = "+" + prop.get("MSISDN").toString().replace("-", "").replace(" ", "");
if(!pruefeRufnummer(rufNr))
{
setRufNrNichtGefunden(rufNr);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date datum = null;
try {
datum = sdf.parse(prop.get("call_start_datetime").toString());
} catch (ParseException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
prepSetRechEintrag.setInt(1, 5);
prepSetRechEintrag.setLong(3, vertragsID);
prepSetRechEintrag.setDate(2, new java.sql.Date(datum.getTime()));
prepSetRechEintrag.executeUpdate();
rst = statKPTools.executeQuery("select max(ID) from rechnungseintrag;");
if(rst.next())
{
prepSetISIMRechEintag.setLong(1, rst.getLong(1));
prepSetISIMRechEintag.setDouble(2, new Double(prop.get("VK netto").toString().replace(",", ".")));
prepSetISIMRechEintag.setDouble(3, new Double(prop.get("EK netto").toString().replace(",", ".")));
prepSetISIMRechEintag.setInt(4, new Integer(prop.get("event_id").toString()));
prepSetISIMRechEintag.setString(5, prop.get("event").toString());
prepSetISIMRechEintag.setLong(6, new Long(prop.get("i_rawcdr").toString()));
prepSetISIMRechEintag.executeUpdate();
Calendar cal = Calendar.getInstance();
cal.setTime(datum);
prepInsertVolumHilfe.setLong(1, vertragsID);
prepInsertVolumHilfe.setInt(2, new Integer(prop.get("event_id").toString()));
prepInsertVolumHilfe.setString(3, prop.get("event").toString());
prepInsertVolumHilfe.setLong(4, new Long(prop.get("charged_quantity").toString()));
prepInsertVolumHilfe.setInt(5, cal.get(Calendar.MONTH));
prepInsertVolumHilfe.setInt(6, cal.get(Calendar.YEAR));
prepInsertVolumHilfe.executeUpdate();
}
}
}
rst.close();
}
The MySQL-Connection Class
package DatenbankConector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import EigeneExceptions.FehlendeLoginDaten;
import Enums.LogLevel;
import Enums.MySQLDatenbanken;
import Hilfsklassen.Logger;
public class MYSQLDB {
private static MYSQLDB loginDB = null;
private static MYSQLDB kptoolsDB = null;
private static MYSQLDB datenImpDB = null;
private static String loginUser = null;
private static String loginPass = null;
private Logger log = Logger.getInstance();
private Connection connect;
private String dbHost = "XXX.XXX.XXX.XXX"; // Hostname
private String dbPort = "3306"; // Port -- Standard: 3306
private String logindbUser = "******"; // Login-Datenbankuser
private String logindbPass = "********"; // Login-Datenbankpasswort
private boolean kannStarten = false;
private MySQLDatenbanken dbEnum;
private MYSQLDB(MySQLDatenbanken db)
{
String strConnect = "";
dbEnum = db;
switch(db)
{
case LOGIN_DB:
strConnect = "jdbc:mysql://"+dbHost+":"+ dbPort+"/logindb?"+"user="+logindbUser+"&"+"password="+logindbPass;
break;
case KPTOOLS_DB:
strConnect = "jdbc:mysql://"+dbHost+":"+ dbPort+"/kptools?"+"user="+loginUser+"&"+"password="+loginPass;
break;
case DATEI_IMP_DB:
strConnect = "jdbc:mysql://"+dbHost+":"+ dbPort+"/dateiimporter?"+"user="+loginUser+"&"+"password="+loginPass;
break;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection(strConnect);
kannStarten = true;
}
catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
kannStarten = false;
}
catch (ClassNotFoundException e) {
log.log(LogLevel.ERROR, e.toString(), this);
kannStarten = false;
}
}
/**
* Gibt eine Instanz von MYSQLDB zurueck.
*
* #param db Angabe welche Datenbank aufgerufen werden soll.
*
* #return ein MYSQLDB Objekt
*
* #throws FehlendeLoginDaten Fehler fals noch keine Logindaten gesetzt wurden.
*/
public static MYSQLDB getInstance(MySQLDatenbanken db) throws FehlendeLoginDaten
{
MYSQLDB obj = null;
switch(db)
{
case LOGIN_DB:
if(loginDB == null)
{
loginDB = new MYSQLDB(MySQLDatenbanken.LOGIN_DB);
obj = loginDB;
} else {
obj = loginDB;
}
break;
case KPTOOLS_DB:
if(kptoolsDB == null)
{
if(loginUser != null && loginPass != null)
{
kptoolsDB = new MYSQLDB(MySQLDatenbanken.KPTOOLS_DB);
obj = kptoolsDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
obj = kptoolsDB;
}
break;
case DATEI_IMP_DB:
if(datenImpDB == null)
{
if(loginUser != null && loginPass != null)
{
datenImpDB = new MYSQLDB(MySQLDatenbanken.DATEI_IMP_DB);
obj = datenImpDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
obj = datenImpDB;
}
break;
}
return obj;
}
/**
* Gibt eine Instanz von MYSQLDB zurueck.
*
* #param db Angabe welche Datenbank aufgerufen werden soll.
* #param user Benutzername für den Datenbanklogin
* #param pass Passwort für den Datenbanklogin
*
* #return ein MYSQLDB Objekt
*
* #throws FehlendeLoginDaten Fehler fals noch keine Logindaten gesetzt wurden.
*/
public static MYSQLDB getInstance(MySQLDatenbanken db, String user, String pass) throws FehlendeLoginDaten
{
MYSQLDB objekt = null;
loginUser = user;
loginPass = pass;
switch(db)
{
case LOGIN_DB:
if(loginDB == null)
{
loginDB = new MYSQLDB(MySQLDatenbanken.LOGIN_DB);
objekt = loginDB;
} else {
objekt = loginDB;
}
break;
case KPTOOLS_DB:
if(kptoolsDB == null)
{
if(loginUser != null && loginPass != null)
{
kptoolsDB = new MYSQLDB(MySQLDatenbanken.KPTOOLS_DB);
objekt = kptoolsDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
objekt = kptoolsDB;
}
break;
case DATEI_IMP_DB:
if(datenImpDB == null)
{
if(loginUser != null && loginPass != null)
{
datenImpDB = new MYSQLDB(MySQLDatenbanken.DATEI_IMP_DB);
objekt = datenImpDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
objekt = datenImpDB;
}
break;
}
return objekt;
}
/**
* Gibt ein Satement Objekt du einer Datenbank zurueck.
*
* #return ein Statement der Datenbankconektion
* #throws SQLException
*/
public Statement getStatement() throws SQLException
{
Statement stat = connect.createStatement();
return stat;
}
/**
* Commitet die Datebankaktionen.
*
* #throws SQLException
*/
public void commit() throws SQLException
{
this.connect.commit();
}
/**
* Gibt ein PreparedStatement zu einem SQL-Statement zurueck.
*
* #param sqlString das SQL-Statement
* #return das PreparedStatement
*/
public PreparedStatement getPreparedStatement(String sqlString)
{
try {
return connect.prepareStatement(sqlString);
} catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
return null;
}
/**
* Schließt eine Datenbankconnection.
*/
public void close()
{
try
{
connect.close();
switch(dbEnum)
{
case LOGIN_DB:
loginDB = null;
break;
case KPTOOLS_DB:
kptoolsDB = null;
break;
case DATEI_IMP_DB:
datenImpDB = null;
break;
}
}
catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
}
/**
* Gibt zurueck ob beim setzen der Datenbankconnektion ein Fehler aufgetreten ist.
*
* #return funktionstuechtig oder nicht
*/
public boolean getKannStarten()
{
return kannStarten;
}
/**
* Setzt die Auto-Commit Variable der Datenbankconnektion
*
* #param autocom true = Auto-Commit
*/
public void setAutoCommit(boolean autocom)
{
try {
connect.setAutoCommit(autocom);
} catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
}
}
Check the error logs in your MySQL server. They should tell you why MySQL terminates the connection.
My guess is that the database limits the size of a transaction. Simply put: You're trying to insert too much data at once.
If that's the case, commit the transaction after every 1000 rows.
java.sql.SQLException: Could not retrieve transation read-only status
Use older version of MySQL .
I tested MySQL-connector JDBC driver with both Appserv version and appserv-win32-2.5.9
With Appserv 2.6 I get the above error.
With Appserv version 5 it works fine.
Two days ago i started learning Cassandra in my internship, they gave me a learning about Cassandra and i found some codes from the net.There is no errors on the code syntatically but when i run the code i get errors like :
InvalidRequestException(why:Keyspace
Blog does not exist in this schema.)
at
org.apache.cassandra.thrift.Cassandra$remove_result.read(Cassandra.java:14354)
at
org.apache.cassandra.thrift.Cassandra$Client.recv_remove(Cassandra.java:755)
at
org.apache.cassandra.thrift.Cassandra$Client.remove(Cassandra.java:729)
at
Authors.removeAuthor(Authors.java:141)
at Authors.main(Authors.java:59)
I am also running cassandra from the console with the ./cassandra -f command.
I think i need to build up a cassandra database first but i really couldn't find how to do it with java.
Please help me about this topic.
Thank you very much.
if it will be helpful the code i am trying is here.
/**
* Sample code for the blog posting:
*
* Installing and using Apache Cassandra With Java Part 4 (Thrift Client)
* http://www.sodeso.nl/?p=251
*
* Please report any discrepancies that you may find,
* if you have any requests for examples not mentioned here
* but are within the scope of the blog posting then also
* please let me know so i can add them..
*/
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.Deletion;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KeyRange;
import org.apache.cassandra.thrift.KeySlice;
import org.apache.cassandra.thrift.Mutation;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
/**
* #author Ronald Mathies
*/
public class Authors {
private static final String KEYSPACE = "Blog";
private static final String COLUMN_FAMILY = "Authors";
public static final String ENCODING = "utf-8";
private static TTransport tr = null;
public static void main(String[] args) throws TException, InvalidRequestException, UnavailableException, UnsupportedEncodingException, NotFoundException, TimedOutException {
Cassandra.Client client = setupConnection();
System.out.println("Remove all the authors we might have created before.\n");
removeAuthor(client, "Eric Long");
removeAuthor(client, "Ronald Mathies");
removeAuthor(client, "John Steward");
System.out.println("Create the authors.\n");
createAuthor(client, "Eric Long", "eric (at) long.com", "United Kingdom", "01/01/2002");
createAuthor(client, "Ronald Mathies", "ronald (at) sodeso.nl", "Netherlands, The", "01/01/2010");
createAuthor(client, "John Steward", "john.steward (at) somedomain.com", "Australia", "01/01/2009");
System.out.println("Select Eric Long.\n");
selectSingleAuthorWithAllColumns(client, "Eric Long");
System.out.println("Select Ronald Mathies.\n");
selectSingleAuthorWithAllColumns(client, "Ronald Mathies");
System.out.println("Select John Steward.\n");
selectSingleAuthorWithAllColumns(client, "John Steward");
System.out.println("Select all authors with all columns.\n");
selectAllAuthorsWithAllColumns(client);
System.out.println("Select all authors with only the email column.\n");
selectAllAuthorsWithOnlyTheEmailColumn(client);
System.out.println("Update John Steward.\n");
updateJohnStewardAuthor(client);
System.out.println("Select John Steward.\n");
selectSingleAuthorWithAllColumns(client, "John Steward");
System.out.println("Remove email address and birthday from John Steward.\n");
deleteEmailAndBirthdayFromJohnSteward(client);
System.out.println("Select John Steward.\n");
selectSingleAuthorWithAllColumns(client, "John Steward");
closeConnection();
}
/**
* Open up a new connection to the Cassandra Database.
*
* #return the Cassandra Client
*/
private static Cassandra.Client setupConnection() throws TTransportException {
try {
tr = new TSocket("localhost", 9160);
TProtocol proto = new TBinaryProtocol(tr);
Cassandra.Client client = new Cassandra.Client(proto);
tr.open();
return client;
} catch (TTransportException exception) {
exception.printStackTrace();
}
return null;
}
/**
* Close the connection to the Cassandra Database.
*/
private static void closeConnection() {
try {
tr.flush();
tr.close();
} catch (TTransportException exception) {
exception.printStackTrace();
}
}
/**
* Removes an Author from the Authors ColumnFamily.
* cccc
* #param client the Corg.apache.thrift;
importassandra Client
* #param authorKey The key of the Author
*/
private static void removeAuthor(Cassandra.Client client, String authorKey) {
try {
ColumnPath columnPath = new ColumnPath(COLUMN_FAMILY);
client.remove(KEYSPACE, authorKey, columnPath, System.currentTimeMillis(), ConsistencyLevel.ALL);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Creates and stores an Author in the Cassandra Database.
*
* #param client the Cassandra Client
* #param authorKey The key of the Author
* #param email the email address
* #param country the country
* #param registeredSince the registration date
*/
private static void createAuthor(Cassandra.Client client, String authorKey, String email, String country, String registeredSince) {
try {
long timestamp = System.currentTimeMillis();
Map<String, List<ColumnOrSuperColumn>> job = new HashMap<String, List<ColumnOrSuperColumn>>();
List<ColumnOrSuperColumn> columns = new ArrayList<ColumnOrSuperColumn>();
Column column = new Column("email".getBytes(ENCODING), email.getBytes(ENCODING), timestamp);
ColumnOrSuperColumn columnOrSuperColumn = new ColumnOrSuperColumn();
columnOrSuperColumn.setColumn(column);
columns.add(columnOrSuperColumn);
column = new Column("country".getBytes(ENCODING), country.getBytes(ENCODING), timestamp);
columnOrSuperColumn = new ColumnOrSuperColumn();
columnOrSuperColumn.setColumn(column);
columns.add(columnOrSuperColumn);
column = new Column("country".getBytes(ENCODING), country.getBytes(ENCODING), timestamp);
columnOrSuperColumn = new ColumnOrSuperColumn();
columnOrSuperColumn.setColumn(column);
columns.add(columnOrSuperColumn);
column = new Column("registeredSince".getBytes(ENCODING), registeredSince.getBytes(ENCODING), timestamp);
columnOrSuperColumn = new ColumnOrSuperColumn();
columnOrSuperColumn.setColumn(column);
columns.add(columnOrSuperColumn);
job.put(COLUMN_FAMILY, columns);
client.batch_insert(KEYSPACE, authorKey, job, ConsistencyLevel.ALL);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Selects a single author with all the columns from the Cassandra database
* and display it in the console.
*
* #param client the Cassandra client
* #param authorKey The key of the Author
*/
private static void selectSingleAuthorWithAllColumns(Cassandra.Client client, String authorKey) {
try {
SlicePredicate slicePredicate = new SlicePredicate();
SliceRange sliceRange = new SliceRange();
sliceRange.setStart(new byte[] {});
sliceRange.setFinish(new byte[] {});
slicePredicate.setSlice_range(sliceRange);
ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY);
List<ColumnOrSuperColumn> result = client.get_slice(KEYSPACE, authorKey, columnParent, slicePredicate, ConsistencyLevel.ONE);
printToConsole(authorKey, result);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Selects all the authors with all the columns from the Cassandra database.
*
* #param client the Cassandra client
*/
private static void selectAllAuthorsWithAllColumns(Cassandra.Client client) {
try {
KeyRange keyRange = new KeyRange(3);
keyRange.setStart_key("");
keyRange.setEnd_key("");
SliceRange sliceRange = new SliceRange();
sliceRange.setStart(new byte[] {});
sliceRange.setFinish(new byte[] {});
SlicePredicate slicePredicate = new SlicePredicate();
slicePredicate.setSlice_range(sliceRange);
ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY);
List<KeySlice> keySlices = client.get_range_slices(KEYSPACE, columnParent, slicePredicate, keyRange, ConsistencyLevel.ONE);
for (KeySlice keySlice : keySlices) {
printToConsole(keySlice.getKey(), keySlice.getColumns());
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Selects all the authors with only the email column from the Cassandra
* database.
*
* #param client the Cassandra client
*/
private static void selectAllAuthorsWithOnlyTheEmailColumn(Cassandra.Client client) {
try {
KeyRange keyRange = new KeyRange(3);
keyRange.setStart_key("");
keyRange.setEnd_key("");
List<byte[]> columns = new ArrayList<byte[]>();
columns.add("email".getBytes(ENCODING));
SlicePredicate slicePredicate = new SlicePredicate();
slicePredicate.setColumn_names(columns);
ColumnParent columnParent = new ColumnParent(COLUMN_FAMILY);
List<KeySlice> keySlices = client.get_range_slices(KEYSPACE, columnParent, slicePredicate, keyRange, ConsistencyLevel.ONE);
for (KeySlice keySlice : keySlices) {
printToConsole(keySlice.getKey(), keySlice.getColumns());
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Update the John Steward author with a new email address and a new field, the birthday.
*
* #param client the Cassandra client
*/
private static void updateJohnStewardAuthor(Cassandra.Client client) {
try {
long timestamp = System.currentTimeMillis();
Map<String, Map<String, List<Mutation>>> job = new HashMap<String, Map<String, List<Mutation>>>();
List<Mutation> mutations = new ArrayList<Mutation>();
// Change the email address
Column column = new Column("email".getBytes(ENCODING), "john#steward.nl".getBytes(ENCODING), timestamp);
ColumnOrSuperColumn columnOrSuperColumn = new ColumnOrSuperColumn();
columnOrSuperColumn.setColumn(column);
Mutation mutation = new Mutation();
mutation.setColumn_or_supercolumn(columnOrSuperColumn);
mutations.add(mutation);
// Add a new column
column = new Column("birthday".getBytes(ENCODING), "05-04-1978".getBytes(ENCODING), timestamp);
columnOrSuperColumn = new ColumnOrSuperColumn();
columnOrSuperColumn.setColumn(column);
mutation = new Mutation();
mutation.setColumn_or_supercolumn(columnOrSuperColumn);
mutations.add(mutation);
Map<String, List<Mutation>> mutationsForColumnFamily = new HashMap<String, List<Mutation>>();
mutationsForColumnFamily.put(COLUMN_FAMILY, mutations);
job.put("John Steward", mutationsForColumnFamily);
client.batch_mutate(KEYSPACE, job, ConsistencyLevel.ALL);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Delete the email address and birthday from John Steward.
*
* #param client the Cassandra client
*/
private static void deleteEmailAndBirthdayFromJohnSteward(Cassandra.Client client) {
try {
long timestamp = System.currentTimeMillis();
// The columns we want to remove
List<byte[]> columns = new ArrayList<byte[]>();
columns.add("email".getBytes(ENCODING));
columns.add("birthday".getBytes(ENCODING));
// Add the columns to a SlicePredicate
SlicePredicate slicePredicate = new SlicePredicate();
slicePredicate.setColumn_names(columns);
Deletion deletion = new Deletion(timestamp);
deletion.setPredicate(slicePredicate);
Mutation mutation = new Mutation();
mutation.setDeletion(deletion);
List<Mutation> mutations = new ArrayList<Mutation>();
mutations.add(mutation);
Map<String, List<Mutation>> mutationsForColumnFamily = new HashMap<String, List<Mutation>>();
mutationsForColumnFamily.put(COLUMN_FAMILY, mutations);
Map<String, Map<String, List<Mutation>>> batch = new HashMap<String, Map<String, List<Mutation>>>();
batch.put("John Steward", mutationsForColumnFamily);
client.batch_mutate(KEYSPACE, batch, ConsistencyLevel.ALL);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Prints out the information to the console.
*
* #param key the key of the Author
* #param result the result to print out
*/
private static void printToConsole(String key, List<ColumnOrSuperColumn> result) {
try {
System.out.println("Key: '" + key + "'");
for (ColumnOrSuperColumn c : result) {
if (c.getColumn() != null) {
String name = new String(c.getColumn().getName(), ENCODING);
String value = new String(c.getColumn().getValue(), ENCODING);
long timestamp = c.getColumn().getTimestamp();
System.out.println(" name: '" + name + "', value: '" + value + "', timestamp: " + timestamp);
} else {
}
}
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
}
}
}
"Keyspace X does not exist" means ... the keyspace doesn't exist. Keyspaces are configured in your storage-conf.xml.
In addition to this, create KeySpace manually be connecting with cassandra with thrift client.
example of it is given in cassandra wiki webpage.
This topic is very old, the best way nowadays is to use datastax
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Running a .sql script using MySQL with JDBC
I have an SQL script file which contains 40-50 SQL statements. Is it possible to run this script file using JDBC?
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* #param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* #param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
I use this bit of code to import sql statements created by mysqldump:
public static void importSQL(Connection conn, InputStream in) throws SQLException
{
Scanner s = new Scanner(in);
s.useDelimiter("(;(\r)?\n)|(--\n)");
Statement st = null;
try
{
st = conn.createStatement();
while (s.hasNext())
{
String line = s.next();
if (line.startsWith("/*!") && line.endsWith("*/"))
{
int i = line.indexOf(' ');
line = line.substring(i + 1, line.length() - " */".length());
}
if (line.trim().length() > 0)
{
st.execute(line);
}
}
}
finally
{
if (st != null) st.close();
}
}
Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:
public void executeSqlScript(Connection conn, File inputFile) {
// Delimiter
String delimiter = ";";
// Create scanner
Scanner scanner;
try {
scanner = new Scanner(inputFile).useDelimiter(delimiter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// Loop through the SQL file statements
Statement currentStatement = null;
while(scanner.hasNext()) {
// Get statement
String rawStatement = scanner.next() + delimiter;
try {
// Execute statement
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
if (currentStatement != null) {
try {
currentStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
currentStatement = null;
}
}
scanner.close();
}
Just read it and then use the preparedstatement with the full sql-file in it.
(If I remember good)
ADD: You can also read and split on ";" and than execute them all in a loop.
Do not forget the comments and add again the ";"
You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.
I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.
You can read the script line per line with a BufferedReader and append every line to a StringBuilder so that the script becomes one large string.
Then you can create a Statement object using JDBC and call statement.execute(stringBuilder.toString()).