一.數(shù)據(jù)庫封裝。
根據(jù)前面執(zhí)行DQL和DDL語句,我們發(fā)現(xiàn),在執(zhí)行數(shù)據(jù)庫操作中,數(shù)據(jù)庫的鏈接以及關(guān)閉方法是相同的,那么,是不是可以將這兩部分代碼單獨提取出來,需要鏈接時只需要調(diào)用就可以呢?
1.驅(qū)動加載
staticStringurl="jdbc:mysql://localhost:3306/test";
staticStringname="root";
staticStringpassword="root";
//靜態(tài)代碼塊只加載一次
static{
try{
Class.forName("com.mysql.jdbc.Driver");
}?? catch(? Exception e? )? {
e.printStackTrace? (?? )?? ;
throw newRuntimeException(?? e? )?? ;??? }??? }
2.數(shù)據(jù)庫鏈接
public??? staticConnection??? getConnection(?? )??? {
Connection?? connection?? =?? null??? ;
try{
??????? connection=DriverManager.getConnection(url,name,password);
}?? catch?? (?? Exception e?? ) ?? {
e.printStackTrace(?? )?? ;? }
returnconnection;?? }
3.鏈接關(guān)閉
public static voidclose(Connection connection,Statement statement){
if(connection!=null){
try{
connection.close();
}catch(Exception e) {
e.printStackTrace();??? }
System.out.println("關(guān)閉成功");?? }
if(statement!=null){
try{
statement.close();
}catch(Exception e) {
e.printStackTrace(? ) ;?? }?? }? }
二.執(zhí)行DML語句
1.調(diào)用jdbcUtil鏈接數(shù)據(jù)庫
public static voidmain(String [] args){
Connection connection=null;
Statement statement=null;
try{
//調(diào)用jdbcUtil鏈接數(shù)據(jù)庫
connection=jdbcUtil.getConnection();
//創(chuàng)建statement對象
statement=connection.createStatement();
}catch(Exception? e)?? {
e.printStackTrace();
throw newRuntimeException(e)? ;? }?? finally{
//關(guān)閉鏈接
jdbcUtil.close(connection,statement)??? ;?? }??? }
2.ResultSet接口:用于封裝查詢出啦的數(shù)據(jù)
boolean next ()將光標(biāo)移動到下一行
getXX()獲取列的值
3.取值的三種方式
1).索引取值
int id=resultSet.getInt(1);
String name=resultSet.getString(2);
System.out.println("id:"+id+"姓名:"+name);
2.)名稱取值
intid=resultSet.getInt("id");
String name=resultSet.getString("name");
System.out.println("id:"+id+"姓名:"+name);
3)遍歷取值
while (resultSet.next()){
int id=resultSet.getInt("id");
String name=resultSet.getString("name");
System.out.println("id:"+id+"姓名:"+name);??? }