gpt4 book ai didi

java - 从 Java 运行 MySql 失败

转载 作者:行者123 更新时间:2023-11-29 07:52:49 26 4
gpt4 key购买 nike

我正在尝试使用 Process exec 从 Java 进程运行 MySql 命令

代码:

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();

当我从命令行运行 sql 查询时,它工作得很好,但是从 Java 进程中我得到 '用法:mysql [选项] [数据库]...以及所有 MySql 选项。

如果没有 -e 参数,它似乎可以工作,没有错误,但当然什么也没有发生。在 Win& 机器中它也运行得很好,但在部署 Linux 机器上则不然。

知道我做错了什么吗?

最佳答案

Java 使用 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;
}
}

取自 here .

关于java - 从 Java 运行 MySql 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25978781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com