📄 queryhelp.java
字号:
package simpleforum.database;
/**
* @author wangmj
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;
public class QueryHelp {
/**
* 传入一个查询sql语句然后将结果放入Vector中。
* 字段名全部为大写,所以像下面这样才能取道正确的值: hash.get("FIELD");
* @param querySql
* @return
*/
public static Vector getHelp(String querySql) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
Vector vector = new Vector();
//这里不能使用空句柄。
//教训,最好不要使用null,除非你能够通过下面的语句取得一个对象。
//String对象也是如此。
try {
connection = DataBaseConn.getConnection();
connection.setReadOnly(true);
statement = connection.prepareStatement(querySql);
resultset = statement.executeQuery();
ResultSetMetaData resultsetmetadata = resultset.getMetaData();
int i = resultsetmetadata.getColumnCount();
String as[] = new String[i];
for (int j = 1; j <= i; j++)
as[j - 1] = (resultsetmetadata.getColumnName(j)).toUpperCase();
//所有的key值均为字段的大写
Hashtable hashtable;
for (; resultset.next(); vector.addElement(hashtable)) {
hashtable = new Hashtable();
for (int k = 1; k <= i; k++) {
Object obj = resultset.getObject(k);
String s = as[k - 1];
if (obj != null)
hashtable.put(s, obj);
else
hashtable.put(s, "");
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultset != null)
resultset.close();
} catch (SQLException e) {
}
try {
if (statement != null)
statement.close();
} catch (SQLException e) {
}
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
}
}
return vector;
}
/**
* 本方法的使用应该注意,只能使用统计函数count(*)例如:
* select count(*) from forumpost where forumid=1;
* @param querySql
* @return
*/
public static int getInt(String querySql) {
int temp = 0;
Connection conn = DataBaseConn.getConnection();
PreparedStatement statement = null;
ResultSet rst = null;
try{
statement = conn.prepareStatement(querySql);
rst = statement.executeQuery();
while(rst.next()){
temp = rst.getInt(1);
}
}catch(SQLException e){
System.out.println("出现异常:\n"+"QueryHelp.getInt("+querySql+")\n");
System.out.println("下面是详细信息:\n");
e.printStackTrace();
}finally{
try {
if (rst != null)
rst.close();
} catch (SQLException e) {
}
try {
if (statement != null)
statement.close();
} catch (SQLException e) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}
return temp;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -