?? dbmanager.java
字號:
package book.rssreader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbManager {
//類成員Connection
protected static Connection conn;
//mysql的驅(qū)動類,定義為常量
public static final String CLASS_NAME = "com.mysql.jdbc.Driver";
//數(shù)據(jù)庫的連接地址,定義為常量
public static final String CONNET_STR = "jdbc:mysql://localhost/rssreader";
//獲得Connetion
public static Connection getConnection() {
try {
Class.forName(CLASS_NAME);//使用類反射加載該驅(qū)動類
//獲得一個Connection
conn = DriverManager.getConnection(CONNET_STR, "root", "");
return conn;//返回該Connection
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//傳入查詢數(shù)據(jù)庫的sql語句,返回ResultSet
public static ResultSet getResultSet(String sql) {
boolean bSuccess = true;
Statement stmt = null;//聲明Statement stmt
ResultSet rs = null;//聲明ResultSet rs
Connection con = getConnection();//調(diào)用getConnetion()方法獲得一個Connetion
if (con == null)//如果Connection 為null則返回假
bSuccess = false;
if (bSuccess) {
try {
stmt = con.createStatement();//通過Connection創(chuàng)建一個Statemet
rs = stmt.executeQuery(sql);//執(zhí)行查詢語句,
} catch (SQLException e) {
e.printStackTrace();
bSuccess = false;
}
}
if (bSuccess)//如果執(zhí)行成功,則返回rs
return rs;
else
return null;
}
//傳入執(zhí)行數(shù)據(jù)更新的語句,返回更新結(jié)果,真為成功執(zhí)行
public static boolean excute(String sql) {
boolean bSuccess = true;
Statement stmt = null;//聲明Statement stmt
Connection con = getConnection();//調(diào)用getConnetion()方法獲得一個Connetion
if (con == null)//如果Connection 為null則返回假
bSuccess = false;
if (bSuccess) {
try {
stmt = con.createStatement();//通過Connection創(chuàng)建一個Statemet
bSuccess = stmt.execute(sql);//執(zhí)行更新數(shù)據(jù)操作
} catch (SQLException e) {
e.printStackTrace();
bSuccess = false;
}
}
return bSuccess;
}
//釋放Connection
public static void releaseConnection() {
try {
if (conn != null)// 如果Connetion 不為null則關(guān)閉Connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -