I'm trying to run MySql command from Java process using Process exec
the code:
String s = "mysql -h192.168.0.1 -u USER -PASSWORD DB_NAME-e \"select * from table\"
System.out.println(s);
Process p = r.exec(s);
p.waitFor();
When I'm running the sql query from command line its works great, but from the Java process I get '
Usage: mysql [OPTIONS] [database]... with all the MySql options.
Without the -e parameter its seems to work, no error but of course nothing happens.
In Win& machine its also works great, not on the deploy Linux machine.
Any ideas what I'm doing wrong?
Example of Java using MySQL:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
// assume that conn is an already created JDBC connection (see previous examples)
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}
Taken from here.
Try this, see if it aids your efforts
http://pastebin.com/XpRyGQBq
Usage:
DBConnectionHandler | new DBConnectionHandler(connectionURL, username*, password*) ResultSet | +query(String sqlStatementGoesHere)
void | +update(String sqlStatementGoesHere)
ResultSet | +getTables()
*means optional
Related
This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);
Why do I get a java.sql.PreparedStatement that is closed from an opened connection to MySQL?
This is my code:
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class MySqlTest1
{
Connection connection = null;
PreparedStatement stmt = null;
public MySqlTest1()
{
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = "jdbc:mysql://localhost:3306/world?autoReconnect=true&useSSL=false";
String username = "jee";
String password = "????????";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password))
{
if (connection.isClosed())
{
System.out.println("Returned connection is closed");
return;
}
System.out.println("Database connected!");
System.out.println("create statement ...");
**stmt = connection.prepareStatement("select * from city");**
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
System.out.println("Selecting data ...");
ResultSet rs = null;
try {
System.out.println("execute query ...");
rs = stmt.executeQuery();
if (rs != null)
{
System.out.println("Data selected");
}
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
return;
}
The result from that code is
Loading driver...
Driver loaded!
Connecting database...
Database connected!
create statement ...
Selecting data ...
execute query ...
****SQLException: No operations allowed after statement closed.****
SQLState: S1009
VendorError: 0
I have tried with the Statement as well and looked into its values and and found that "isClosed" is true.
I have looked into the MySQL log but found nothing.
You are opening the connection in a try-with-resource block. Once the block is terminated, the connection is closed, and implicitly, all the statements created from it. Just extend this block to include the usage of the statement, and you should be OK.
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.
while I'm able to connect and query an oracle database using Oracle SQLDeveloper, I'n not able to do the same from a test java application:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#myhost:1521/mysid"; //SID
//String url = "jdbc:oracle:thin:#myhost:1521:myservice"; //service
String usr = "myuser";
String pwd = "mypassword";
System.out.print("Before DriverManager...");
con = DriverManager.getConnection(url, usr, pwd);
if (con == null)
{
System.out.print("Connection is null");
}
else
{
System.out.print("Connection OK");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT count(*) FROM mytable");
while(rs.next()) {
System.out.print(rs.getInt(1));
//System.out.println(rs.getString(2));
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Some system details:
OS: Mac OS X 10.9.4
Java Version: 1.7
Eclipse: Kepler (64bit)
Oracle Client: instantclient_10_2
After some unsuccessful tentatives, I decided to copy exactly the same JDBC driver used by SQLDeveloper (using show package content). I've copied it under my project folder/lib. And then I added the jar to the build path.
When I run the application on my mac it just remain stuck after printing "Before DriverManager..."
If I run the same application on a colleague windows machine it works fine and print the count results.
I'm really out of options, and I'm starting to think there's some issue with my machine java permission. Is it possible? Any idea where I should look for?
Any help is appreciated.
Regards
Stefano
I have a funny requirement.
We need to have a command-line interaction in a Java Stored Procedure. In spite of granting appropriate permissions using the dbms_java.grant_permission commands, I am encountering java.io.IOException, where I read from System.in using java.io.InputStreamReader.
Where is the problem?
The Java Source is here:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
public class ExecuteInteractiveBatch {
public static void aFunction() {
Connection connection = null;
try {
int rowFetched = 0;
connection = new OracleDriver().defaultConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(1) cnt from sometable where c = 2");
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
stmt.close();
rs = null;
stmt = null;
if (count == 1) {
System.out.println("Do you want to continue?");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String response = reader.readLine();
if ("Y".equalsIgnoreCase(response)) {
stmt = connection.createStatement();
int rowsAffected = stmt.executeUpdate("DELETE from sometable where c=2");
System.out.println("" + rowsAffected + " row(s) deleted");
stmt.close();
}
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
You can't perform I/O to the console from within Oracle... not in java, not in PL/SQL, nowhere. Oracle is running in a separate process from the user, quite likely even a different computer, and java stored procedures are being run in that process. You will need some java code running on the client system to perform console I/O.