import java.sql.*;
public class DB2conn{
/**設置參數**/
private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
/**設置參數**/
private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
/**構造方法,鏈接數據庫**/
public DB2conn() {
try{
System.out.println("正在連接數據庫..........");
Class.forName("com.ibm.db2.jcc.DB2Driver");//加載mysql驅動程序類
String url = "jdbc:db2://localhost:50000/toolsdb";//url為連接字符串
String user = "db2admin";//數據庫用戶名
String pwd = "1234";//數據庫密碼
conn=(Connection)DriverManager.getConnection(url,user,pwd);
System.out.println("數據庫連接成功!!!");
}catch(Exception e){
System.out.println(e.getMessage());
//e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
DB2conn a = new DB2conn();//實例化對象,作用是調用構造方法
a.getClass();//無意義
/**查詢語句**/
String sql="select * from person";
stmt = (Statement) conn.createStatement();
stmt.execute(sql);//執行select語句用executeQuery()方法,執行insert、update、delete語句用executeUpdate()方法。
rs=(ResultSet) stmt.getResultSet();
while(rs.next()){ //當前記錄指針移動到下一條記錄上
int i = rs.getInt(1);//得到當前記錄的第一個字段(id)的值
String name =rs.getString(2);//得到第二個字段(name)的值
String psw = rs.getString("ppassword");//得到(password)的值
System.out.println(Integer.toString(i)+" "+name+" "+psw);
}
rs.close();//后定義,先關閉
stmt.close();
conn.close();//先定義,后關閉
}
}