package test;
import java.util.*;
import java.sql.*;
/**
*
* @author huypv
*/
public class Db {
private String _host;
private String _port;
private String _username;
private String _password;
private String _dbname;
private Connection _conn;
private ResultSet _result;
public Db() {
this._host = "127.0.0.1";
this._port = "3306";
this._username = "root";
this._password = "";
this._dbname = "mysql";
}
public boolean connect() {
try {
this._conn = DriverManager.getConnection ("jdbc:mysql://" + this._host + ":" + this._port + "/" + this._dbname , this._username, this._password);
} catch (Exception e) {
System.err.println("Connect Error: " + e.getMessage());
}
return true;
}
public void close() {
try {
this._conn.close();
} catch (Exception e) {}
}
public void query(String sql) {
Statement stmt;
this._result = null;
try {
stmt = this._conn.createStatement();
this._result = stmt.executeQuery (sql);
} catch (Exception e) {
System.err.println("Query Error: " + e.getMessage());
}
}
public Map fetchRow() {
Map<String, Object> mp = new HashMap<String, Object>();
try {
ResultSetMetaData rsmd = this._result.getMetaData();
if (!this._result.next()) return mp;
int numCols = rsmd.getColumnCount();
for (int i = 0; i < numCols; i++)
mp.put(rsmd.getColumnLabel(i+1), this._result.getString(i+1));
} catch (Exception e) {
System.err.println(e.getMessage());
}
return mp;
}
public Map[] fetchRowSet() {
Map[] ret = null;
try {
if (!this._result.next()) return ret;
ResultSetMetaData rsmd = this._result.getMetaData();
int numCols = rsmd.getColumnCount();
this._result.last();
int numRows = this._result.getRow();
ret = new Map[numRows];
this._result.first();
Map<String, Object> mp = null;
for (int r = 0; r < numRows; r++) {
mp = new HashMap<String, Object>();
for (int i = 0; i < numCols; i++) {
//mp.put(rsmd.getColumnName(i+1), this._result.getString(i+1));
mp.put(rsmd.getColumnLabel(i+1), this._result.getString(i+1));
}
ret[r] = mp;
this._result.next();
}
} catch (Exception e) {
System.err.println("Fetch RowSet Error: " + e.getMessage());
}
return ret;
}
}
Title:
Java MySQL Connector ResultSet Fetch Data
Description:
package test; import java.util.*; import java.sql.*; /** * * @author huypv */ public class Db { private String _host; p...
...
Rating:
4