I wrote the following code to restore MySQL backup ,
public boolean restoreDB(String dbUserName, String dbPassword) {
try {
NewClassx n = new NewClassx();
n.myf(2);
String source = jTextField1.getText();
Process runtimeProcess;
Connection con = CPool.getConnection();
Statement stmt = con.createStatement();
ResultSet res = null;
res = stmt.executeQuery("select ##datadir");
String Mysqlpath = "";
while (res.next()) {
Mysqlpath = res.getString(1);
}
Mysqlpath = Mysqlpath.replace("data", "bin");
CPool.closeConnection(con);
CPool.closeStatement(stmt);
CPool.closeResultSet(res);
// String[] executeCmd = new String[]{Mysqlpath + "\\mysql", "--user=" + dbUserName, " -e", "source " + "\"" + source + "\""};
// String executeCmd = Mysqlpath + "\\mysql - u "+ dbUserName +" -e "+ "\"" + source + "\"";
//mysql - u admin -p admin accounts <
String[] executeCmd = new String[]{Mysqlpath + "\\mysql", " project_db ", " --user=" + dbUserName, " -e", " source "+ " \"" + source + "\""};
// System.out.println(executeCmd);
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
JOptionPane.showInternalMessageDialog(this, "Backup restored successfully");
return true;
} else {
JOptionPane.showInternalMessageDialog(this, "Backup was not restored");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
on calling the above function , my application freezes without restoring any backup.
you didn't write password in string
add '-p password' after username
Related
i have some issues when i'm run the program. It says "[SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)" and "ada yang salah:java.sql.SQLException: ResultSet is TYPE_FORWARD_ONLY". Am i passed something or what?
connection code
public void koneksiDatabase(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:C:/Users/sqlite3/cekresi.db","root","");
System.out.println("Koneksi berhasil!");
}catch(ClassNotFoundException eclass){
System.out.println("Koneksi Gagal!");
}catch(SQLException esql){
System.out.println(esql.getMessage());
}
}
savedata code
public void simpanData(){
try {
String sql = "Insert into data resi = \"" + txtResi.getText() + "\","
+ "nama = \"" + txtNama.getText() + "\","
+ "tujuan = \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ "tarif = \"" + txtTarif.getText() + "\","
+ "berat = \"" + txtBerat.getText() + "\","
+ "jumlah = \"" + txtJumlah.getText() + "\"";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
System.out.println("berhasil!");
}catch (Exception e){
System.out.println(e);
}
tampilDataKeTabel();
}
showtable code
public void tampilDataKeTabel(){
ResultSet rs = null;
try{
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from data");
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while (rs.next()){
baris = rs.getRow();
}
dataTable = new String[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()){
dataTable[x][0] = rs.getString("resi");
dataTable[x][1] = rs.getString("nama");
dataTable[x][2] = rs.getString("tujuan");
dataTable[x][3] = rs.getString("tarif");
dataTable[x][4] = rs.getString("berat");
dataTable[x][5] = rs.getString("jumlah");
x++;
}
tabelDisplay.setModel(new DefaultTableModel(dataTable,header));
}catch(Exception e){
System.err.println("ada yang salah:"+e);
}
}
There are syntax issues in the insert statement. The syntax should be:
INSERT INTO table (column1,column2 ,..)
VALUES( value1, value2 ,...);
So your insert statement should be something like:
String sql = "Insert into data(resi,nama,tujuan,tarif,berat,jumlah)
values(\"" + txtResi.getText() + "\","
+ \"" + txtNama.getText() + "\","
+ \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ \"" + txtTarif.getText() + "\","
+ \"" + txtBerat.getText() + "\","
+ \"" + txtJumlah.getText() + "\")";
Also, there is an issue in the code to show the data.
while (rs.next()){
baris = rs.getRow();
}
This loop is traversing the result set once. So the next loop would fail as rs has already reached the end of results.
This is causing the exception : ResultSet is TYPE_FORWARD_ONLY
Instead of creating a 2D string array, Create a class corresponding to your db table and then create a List. Assuming a class named Data would be created, the second while loop would be :
List<Data> dataList = new ArrayList<>();
while(rs.next()){
Data data = new Data();
data.setResi(rs.getString("resi"));
data.setNama(rs.getString("nama"));
data.setTujuan(rs.getString("tujuan"));
data.setTarif(rs.getString("tarif"));
data.setBerat(rs.getString("berat"));
data.setJumlah(rs.getString("jumlah"));
dataList.add(data);
}
we get out of memory (the process go up and consumes %100 of ram) trying to select data and insert it into SQLite DB, the program written in java, and the data are so big, we even made pagination for it, it selects 100000 rows and inserts it into SQLite database, to figure out the problem, we commented out all line from the code that insert the data, and we saw that consumption of ram stop's at %6
package dbex;
import java.sql.*;
import java.util.ArrayList;
public class DBEX {
String url = "jdbc:oracle:thin:#192.168.120.46:1521:db";
String user = "dbuser";
String password = "dbpass";
ArrayList<Table> Tales = new ArrayList<>();
public static void main(String[] args) {
DBEX db = new DBEX();
db.CreateDB();
}
public int CountRecords(String table) {
int result = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection getCountCon = DriverManager.getConnection(url, user, password);
Statement CountSt = getCountCon.createStatement();
ResultSet countRs = CountSt.executeQuery("SELECT COUNT(*) as num FROM " + table);
while (countRs.next()) {
result = countRs.getInt("num");
}
} catch (Exception ex) {
}
return result;
}
public void dumpData() {
try {
int incrementRecord = 100000;
Class.forName("org.sqlite.JDBC");
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Table table = null;
ArrayList<String> columns = new ArrayList<>();
Connection getDataCon = DriverManager.getConnection(url, user, password);
getDataCon.setAutoCommit(false);
Statement dataSt = getDataCon.createStatement();
dataSt.setFetchSize(incrementRecord);
ResultSet dataRs = null;
Connection LiteInsertCon = DriverManager.getConnection("jdbc:sqlite:" + "DBEX" + ".db");
LiteInsertCon.setAutoCommit(false);
PreparedStatement insertStatement = null;
int numRecord = 0;
for (int i = 0; i < Tales.size(); i++) {
table = Tales.get(i);
String tableName = table.name;
System.out.println("table::" + tableName);
System.out.println("Dumping data from " + tableName);
String InsertSQL = "INSERT INTO " + tableName + " ( ";
String vals = "VALUES (";
String selectSQL = "SELECT * FROM ( SELECT b.*, ROWNUM RN FROM ( SELECT ";
System.out.println("geting column name...");
columns = table.Columns;
for (int j = 0; j < columns.size(); j++) {
String columnName = columns.get(j);
if (j == 0) {
vals += " ? ";
InsertSQL += columnName + " ";
selectSQL += columnName + " ";
}else {
InsertSQL += " , " + columnName + " ";
vals += ", ? ";
selectSQL += " , " + columnName + " ";
}
}
System.out.println("Number of column of table " + tableName + " is " + columns.size());
vals += ")";
InsertSQL += ")" + vals;
selectSQL += "FROM " + tableName + " ORDER BY "+table.primary_key+" ASC ) b WHERE ROWNUM <= :TO ) WHERE RN > :FROM ";
System.out.println(selectSQL);
System.out.println(InsertSQL);
int parIndex = 0;
String colName = null;
String data = null;
numRecord = CountRecords(tableName);
int from = 0;
int to = incrementRecord;
if (to > numRecord) {
System.out.println("Table data is less than "+incrementRecord+" geting all data "+numRecord+" " );
dataRs = dataSt.executeQuery(selectSQL.replace(":TO", numRecord + "").replace(":FROM", "0"));
while (dataRs.next()) {
insertStatement = LiteInsertCon.prepareStatement(InsertSQL);
insertStatement.setFetchSize(incrementRecord);
for (; parIndex < columns.size(); parIndex++) {
colName = columns.get(parIndex);
data = dataRs.getString(colName);
if (data != null) {
insertStatement.setString(parIndex + 1, data);
} else {
insertStatement.setString(parIndex + 1, " ");
}
parIndex++;
}
parIndex = 0;
insertStatement.executeUpdate();
insertStatement = null;
}
} else {
while (numRecord >= to) {
System.out.println("page "+(to/incrementRecord)+" of "+(numRecord/incrementRecord) );
dataRs = dataSt.executeQuery(selectSQL.replace(":TO", to + "").replace(":FROM", from+""));
while (dataRs.next()) {
insertStatement = LiteInsertCon.prepareStatement(InsertSQL);
insertStatement.setFetchSize(incrementRecord);
for (; parIndex < columns.size(); parIndex++) {
colName = columns.get(parIndex);
data = dataRs.getString(colName);
if (data != null) {
insertStatement.setString(parIndex + 1, data);
} else {
insertStatement.setString(parIndex + 1, " ");
}
parIndex++;
}
parIndex = 0;
insertStatement.executeUpdate();
insertStatement = null;
}
dataRs=null;
from = to;
to += incrementRecord;
System.gc();
}
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
class Table {
public String name;
public String primary_key;
ArrayList< String> Columns = new ArrayList<>();
public Table(String name, String primary_key, ArrayList< String> Columns) {
this.name = name;
this.primary_key = primary_key;
this.Columns = Columns;
}
}
public void CreateDB() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Oracle JDBC driver found");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection getTableCon = DriverManager.getConnection(url, user, password);
Connection getColumnCon = DriverManager.getConnection(url, user, password);
Connection getKeyCon = DriverManager.getConnection(url, user, password);
System.out.println("connected to database");
Statement getTableSt = getTableCon.createStatement();
PreparedStatement getColumnSt = getColumnCon.prepareStatement("SELECT DISTINCT column_name FROM all_tab_cols WHERE table_name = ? ");
PreparedStatement getKeySt = getKeyCon.prepareStatement("SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = ? AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position");
ResultSet getTableRs = getTableSt.executeQuery("SELECT * FROM all_tables WHERE OWNER not in('SYS','OUTLN','SYSTEM')");
ResultSet getColumnRs;
ResultSet getKeyRs;
Class.forName("org.sqlite.JDBC");
System.out.println("Sqlite JDBC driver found");
Connection LiteCreateTableCon = null;
LiteCreateTableCon = DriverManager.getConnection("jdbc:sqlite:" + "DBEX" + ".db");
Statement statement = LiteCreateTableCon.createStatement();
String keyName = "";
while (getTableRs.next()) {
String tableName = getTableRs.getString("table_name");
System.out.println("table: " + tableName);
getColumnSt.setString(1, tableName);
System.out.println("SELECT * FROM all_tab_cols WHERE table_name = " + tableName + "");
getColumnRs = getColumnSt.executeQuery();
String createTableSQL = "create table if not exists " + tableName + " ( ";
int index = 0;
ArrayList<String> Columns = new ArrayList<>();
while (getColumnRs.next()){
String columnName = getColumnRs.getString("column_name");
Columns.add(columnName);
System.out.println("column: " + columnName);
if (index == 0) {
createTableSQL += columnName + " string";
} else {
createTableSQL += " , " + columnName + " string";
}
index++;
}
createTableSQL += ")";
System.out.println(createTableSQL);
statement.executeUpdate(createTableSQL);
getKeySt.setString(1, tableName);
getKeyRs = getKeySt.executeQuery();
keyName = "1";
while (getKeyRs.next()) {
keyName = getKeyRs.getString("column_name");
}
Tales.add(new Table(tableName, keyName, Columns));
}
getTableCon.close();
getColumnCon.close();
getKeyCon.close();
System.out.println("All table created...");
}catch (Exception ex) {
System.out.println(ex.toString());
}
dumpData();
}
}
You need to issue/excute commit on SQLite after inserting every batch of records.
And try to come-up with suitable batch size (may be 100).
This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 5 years ago.
I am using the MySQL connector to get the URL to find values on the web pages.
I am getting the above message and I am not sure why. It inserts the first record from the rs1, but I am not sure why it is closing it.
Below is my code
String strSQL = "SELECT * FROM element_info;";
String sElementID = "";
String sSymbol = "";
URL urlChartLink;
URLConnection urlconn;
String sChartLink = "";
String sCurrentPrice = "";
String FindValue = "last_last";
try {
Class.forName(driver).newInstance();
Connection mysqlconn = DriverManager.getConnection(url + dbName, userName, password);
Statement st1 = mysqlconn.createStatement();
ResultSet rs1 = st1.executeQuery(strSQL);
while (rs1.next()) {
// Get all of the elements
// Retrieve the ElementID
sElementID = rs1.getString(1);
// Retrieve the Symbol
sSymbol = rs1.getString(2);
// Retrieve the Chartlink
sChartLink = rs1.getString(3);
if (sChartLink == "") {
break;
}
try {
urlChartLink = new URL(sChartLink);
urlconn = urlChartLink.openConnection();
urlconn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
BufferedReader in = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));
String currentLine;
while ((currentLine = in.readLine()) != null) {
// See if the value is on this record
int pos1 = currentLine.indexOf(FindValue);
int pos2 = currentLine.indexOf("</span>");
// pos1 = 66
if (pos1 > 0) {
pos1 = pos1 + 21;
pos2 = pos2 - 1;
// System.out.print("pos1 = " + pos1 + "\n");
// System.out.print("pos2 = " + pos2 + "\n");
sCurrentPrice = currentLine.substring(pos1, pos2);
// System.out.print("sCurrentPrice = " + sCurrentPrice + "\n");
// Import into the marketprices
strSQL = "INSERT INTO marketprices"
+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"
+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
int val = st1.executeUpdate(strSQL);
if (val == 1)
System.out.print("Successfully inserted from " + sChartLink + "\n");
break;
}
}
in.close();
} catch (IOException e) {
System.out.print("Error getting ChartLink website: " + e.getMessage() + "\n");
break;
}
}
} catch (Exception e) {
System.out.print("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
You are trying to write with a statement object that is already in use as you are still reading the existing resultset from that statement object. You need to create a new statement object for the update portion of your code:
strSQL = "INSERT INTO marketprices"+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
Connection mysqlconn2 = DriverManager.getConnection(url + dbName, userName, password);
Statement st2 = mysqlconn.createStatement();
int val = st2.executeUpdate(strSQL);
I want to import mysql database using java on web application but unfortunately the mysql.exe process get stuck and next Line of code does not get executed which make browser to keep on loading.
restore.xhtml
<h:panelGrid columns="1" style="margin: 0 auto;">
<p:commandButton value="1 click restore"
action="#restoreBean.oneClickRestore()}" update="all,g" ajax="false"/>
</h:panelGrid>
RestoreBean.java
String absPath ="C:/Users/sms/build/web/resources/backup/backuproot.sql";
String[] executeCmd = new String[]{"mysql ", dbName, "-u " + dbUser, "-p " + dbPwd, "-e ", " \"source "+ absPath+" \""};
try{
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();// after this line no line of code get executed; in taskmanager u can see mysql.exe
if (processComplete == 0) {
restoreMsg = "Successfully restored from SQL : " + absPath;
} else {
restoreMsg = "Error at restoring";
}
} catch (InterruptedException ex) {
Logger.getLogger(RestoreBean.class.getName()).log(Level.SEVERE, null, ex);
}
But the same code runs well and database get imported when used in console application
RestoreDbTest.java
public class RestoreDbTest{
public static void main(String[] args) {
RestoreDbTest b = new RestoreDbTest();
b.restoreDatabase("root", "", "b.sql");
}
public boolean restoreDatabase(String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql ", dbName, "-u " + dbUser, "-p " + dbPwd, "-e ", " \"source b.sql \""};
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
// log.info("Backup restored successfully with " + source);
return true;
} else {
//log.info("Could not restore the backup " + source);
}
} catch (Exception ex) {
System.out.println(ex.getCause());
}
return false;
}
}
mysql process list
I would like to send a broadcast message to all numbers returned from the select statement. It saves elements in the list but then it sends the same message to everyone. What am I doing wrong? Please see my method below.
public static List<Message> listAllMessages(Connection connection) {
List<Message> msg = new ArrayList<Message>();
String messages = ReturnTexts.getMessage(connection, "EMPTYMESSAGE");
String sql = "SELECT b.`productid` as productid, p.`productname` as productname, b.`msisdn` as msisdn , MAX(b.`amount`) as amount, b.`productcode` as productcode, a.`endDate` as enddate FROM "
+ TableNames.SAVEDBIDSTABLE
+ "b LEFT JOIN "
+ TableNames.PRODUCTTABLE1
+ " p ON b.`productcode`= p.`code` "
+ " JOIN "
+ TableNames.AUCTIONTABLE1
+ " a"
+ " ON b.`productcode`= a.`productcode` "
+ "GROUP BY msisdn, productcode ";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
if (connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
// LOGGER.info(sql);
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
// statement = connection.createStatement();
resultSet = statement.executeQuery();
long productid = 0;
String productname = null;
String msisdn = null;
int amount = 0;
String productcode = null;
Date enddate = null;
while (resultSet.next()) {
productid = resultSet.getLong("productid");
productname = resultSet.getString("productname");
msisdn = resultSet.getString("msisdn");
amount = resultSet.getInt("amount");
productcode = resultSet.getString("productcode");
enddate = resultSet.getTimestamp("enddate");
msg.add(new Message(Long.valueOf(productid), productname,
msisdn, amount, productcode, String.valueOf(enddate)));
}
String messages = ReturnTexts
.getMessage(connection, "BROADCAST")
.replace("XXXX", productname)
// .replace("YYYY", String.valueOf(amount))
.replace("YYYY",
String.valueOf(maxBid(productcode, connection)))
.replace("ZZZZ", String.valueOf(enddate));
//LOGGER.info(messages.toString());
try {
for (Message obj : msg) {
obj.setMessage(messages);
String apiUrl = "url/sendsms.jsp";
getResponse(apiUrl + "?" + "user="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&password="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&mobiles=" + obj.getMsisdn() + "&sms="
+ URLEncoder.encode(obj.getMessage(), "UTF-8"));
//bulkMessagesLog(obj.getMsisdn(), obj.getMessage(),obj.getProductcode(), connection);
bulkMessagesLog(productcode, msisdn, productname, connection);
//LOGGER.info(obj.getMsisdn() + " : " + obj.getProductcode()+ " : " + obj.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.err
.println("UnsupportedEncodingException while trying to send SMS.");
e.getMessage();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
} finally {
DBConnection.closeAllDBUsage(resultSet, statement, null);
}
return msg;
}
public static void bulkMessagesLog(String msisdn, String message,String productcode,
Connection connection) {
PreparedStatement statement = null;
String sql = "INSERT INTO " + TableNames.BULK_MESSAGESLOGTABLE
+ "(`msisdn`,`message`,`productcode`,`dateCreated`) VALUES(?,?,?,now()) ";
try {
if ( connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
statement.setString(1, msisdn);
statement.setString(2, message);
statement.setString(3, productcode);
//statement.addBatch();
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
DBConnection.closeAllDBUsage(null, statement, connection);
}
}
You do iterate over the result set and build a list of messages in msg. Though you only create the text once, outside of the loop, so it's always the same with the (last) productname etc.
Should probably also be created in the loop.