import Java.sql.*;
import Java.util.Vector;
import Javax.swing.table.DefaultTableModel;
import Javax.swing.table.TableModel;
public class dbConnection {
Connection conn;
Statement stml;
ResultSet rs;
public Connection getConn() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=Permission";
try {
conn = DriverManager.getConnection(url, "sa", "770417");
return conn;
} catch (SQLException e1) {
return null;
}
public ResultSet getRs(String sql) {
if (conn == null) {
conn = getConn();
}
try {
Statement stml = conn.createStatement();
rs = stml.executeQuery(sql);
return rs;
} catch (SQLException e) {
return null;
}
}
public Vector getVector(String sql) {
Vector name = new Vector();
if (rs == null) {
rs = getRs(sql);
}
try {
while (rs.next()) {
name.addElement(rs.getString(1));
}
return name;
} catch (SQLException e) {
return null;
}
}
// 返回表頭
public Vector getTableTitle(String sql) {
Vector tableTitle = new Vector();
if (rs == null) {
rs = getRs(sql);
}
// 獲得表字段的個數: rs.getMetaData().getColumnCount()
try {
// System.out.println(rs.getMetaData().getColumnCount());
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
tableTitle.addElement(rs.getMetaData().getColumnName(i));
}
return tableTitle;
} catch (SQLException e) {
return null;
}
}
/// 表的主體
public Vector getTableContent(String sql) {
if (rs == null) {
rs = getRs(sql);
}
Vector contentV = new Vector();
try {
while (rs.next()) {
Vector rowV = new Vector();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++)
{
rowV.addElement(rs.getString(i));
}
contentV.addElement(rowV);
}
return contentV;
} catch (SQLException e) {
return null;
}
}
public TableModel getTableModel(String sql) {
TableModel model = new DefaultTableModel(getTableContent(sql),
getTableTitle(sql));
return model;
}
public static void main(String args[]) {
dbConnection db = new dbConnection();
// Vector v=db.getTableTitle("select userId 編號,userName 用戶名,passWord 密碼
// from [user]");
// for(int i=0;i<v.size();i++){
// System.out.println(v.get(i));
// }
Vector content = db.getTableContent("select * from [user]");
for (int i = 0; i < content.size(); i++) {
Vector row = (Vector) content.get(i);
for (int j = 0; j < row.size(); j++) {
System.out.print(row.get(j));
}
System.out.println();
}