我试图创建一个程序,我可以在textarea中键入任何sql语句,然后它将执行它。如果它不是一个查询,那么只是在标签中显示受影响的行,或者如果它是一个查询,则显示结果。我知道如何使用结果集填充jtable。但我有点卡住查询与非查询部分。
答案 0 :(得分:0)
你可能会像......一样:
package default;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
public class DBConnector {
private static Connection getConnection() throws SQLException
{
String url = "your-url";
String user = "user";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public Vector<Vector<String>> ExecuteQuery(String query)
{
Statement stmt = null;
ResultSet rs = null;
//Vector of vectors for JTable
Vector<Vector<String>> data = new Vector<Vector<String>>();
try {
//Create new statement
stmt = getConnection().createStatement();
//Execute given `query`
rs = stmt.executeQuery(query);
if (stmt.execute(query)) {
rs = stmt.getResultSet();
}
//while there are some rows
while(rs.next())
{
//Create new Vector
Vector<String> temp = new Vector<String>();
int numColumns = rs.getMetaData().getColumnCount();
//Put data into that vector
for ( int i = 1 ; i <= numColumns ; i++ ) {
temp.addElement(rs.getString(i));
}
//Add vector to `data`
data.add(temp);
}
}
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 {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { }
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}
//Return
return data;
}
}
首先你需要填充getConnection()
个字段,然后你可以通过调用ExecuteQuery
传递TextArea.getText()
字符串来创建JTable,因为你会得到Vector of Vectors传递给JTable。 / p>
希望我帮助过:)