背景:
前幾天寫連接數據庫時,因為要執行sql,有的是指向得到所有的執行結果,有的是想根據執行結果獲得某一個字段的結果。這時我想通過同一個方法名,不同的參數,獲得不同的結果。結果發現java的方法竟然不能對參數設置默認值==,而是可以通過重載來實現這個過程的。(當然不排除我對java不了解的緣故,如果大家有什么方法可以告訴我謝謝~)
重載:可以理解為同一個方法名,不同的參數,大概的實例如下:
def void A(int i){
#使用參數i的方法A
}
def void A(int j,int k){
#使用參數j和k的方法A
}
說明:這樣可以通過調用同一個方法名,給予不同的參數,實現不同的效果。
特別備注:如果方法和參數均相同,是只可以存在一個方法的,因為我開始想通過相同參數、相同方法名,返回int和String兩種類型的結果,這樣是不可以,只能重新定義一個方法名。
附上錯誤實例:
public int A(String i){
return 一個int類型的結果
}
public String A(String i){
return 一個String類型的結果
}
最后,附上一個我通過重載實現的sql執行的結果,一個是只獲得了查詢結果,一個是獲得了具體字段的內容:
public ResultSet getresult(String sql) {
try {
this.rs = this.stmt.executeQuery(sql);
// System.out.print(this.rs);
// while (rs.next()) {
// long info_id = rs.getLong("info_id");
// System.out.println("\ninfo_id:" + info_id);
// }
return this.rs;
}catch (SQLException e){
System.out.println("SQL中找不到要查找的字段!");
e.printStackTrace();
return this.rs;
}
}
//該方法是直接獲得了要找的字段名對應的結果,只取一條,所以會不斷的覆蓋,取到最后一條,試用與sql結果只有一個的情況,如果是結果是好多行數據,需要用ExcuteSql的方法
public String getresult(String sql,String key){
try {
this.rs = this.stmt.executeQuery(sql);
}catch (SQLException e){
System.out.println("SQL中找不到要查找的字段!");
e.printStackTrace();
}
try{
while(this.rs.next()) {
this.result = this.rs.getString(key);
}
}catch (Exception e){
System.out.println("SQL獲取結果異常!");
e.printStackTrace();
}
return this.result;
}
try {
this.rs = this.stmt.executeQuery(sql);
// System.out.print(this.rs);
// while (rs.next()) {
// long info_id = rs.getLong("info_id");
// System.out.println("\ninfo_id:" + info_id);
// }
return this.rs;
}catch (SQLException e){
System.out.println("SQL中找不到要查找的字段!");
e.printStackTrace();
return this.rs;
}
}
//該方法是直接獲得了要找的字段名對應的結果,只取一條,所以會不斷的覆蓋,取到最后一條,試用與sql結果只有一個的情況,如果是結果是好多行數據,需要用ExcuteSql的方法
public String getresult(String sql,String key){
try {
this.rs = this.stmt.executeQuery(sql);
}catch (SQLException e){
System.out.println("SQL中找不到要查找的字段!");
e.printStackTrace();
}
try{
while(this.rs.next()) {
this.result = this.rs.getString(key);
}
}catch (Exception e){
System.out.println("SQL獲取結果異常!");
e.printStackTrace();
}
return this.result;
}