import?java.sql.Connection;??
import?java.sql.DriverManager;??
import?java.sql.ResultSet;??
import?java.sql.SQLException;??
import?java.sql.Statement;??
public?class?JDBCTest?{??
//?定義數(shù)據(jù)庫訪問參數(shù)??
String?url?="jdbc:sqlserver://localhost:1433;?DatabaseName=lihongchao";??
String?user?="sa";??
String?password?="a123456";??
static?String?driverName?=?"com.microsoft.sqlserver.jdbc.SQLServerDriver";??
?????Connection?conn;??
?????Statement?st;??
//?1、加載驅(qū)動??
static?{??
try?{??
????????????Class.forName(driverName);??
}catch?(ClassNotFoundException?e)?{??
System.out.println("驅(qū)動加載失敗");??
????????}??
????}??
//?2、創(chuàng)建連接對象??
public??Connection?getConnection()?throws?SQLException{??
????????conn=DriverManager.getConnection(url,user,password);??
return?conn;??
????}??
public??void?add()?throws?ClassNotFoundException,?SQLException?{??
//?定義sql語句??
String?sql1="insert?into?Table2(id,name,grade)?values('20121114','大學(xué)英語',3)";??
String?sql2="insert?into?Table2(id,name,grade)?values('20121115','體育',2)";??
String?sql3="insert?into?Table2(id,name,grade)?values('20121116','馬克思',3)";??
//?3、創(chuàng)建語句對象??
????st?=getConnection().createStatement();??
//?st.executeUpdate(sql1);??
????st.executeUpdate(sql2);??
????st.executeUpdate(sql3);??
//?4、遍歷結(jié)果集:此處插入記錄不需要??
//?5、關(guān)閉資源對象??
?????st.close();??
?????getConnection().close();??
}??
public??void?update()?throws?ClassNotFoundException,?SQLException?{??
//?定義sql語句??
String?sql1="update?Table2?set?grade=1??where?grade=2";??
//?3、創(chuàng)建語句對象??
????????st?=getConnection().createStatement();??
????????st.executeUpdate(sql1);??
//?4、遍歷結(jié)果集:此處插入記錄不需要??
//?5、關(guān)閉資源對象??
?????????st.close();??
?????????getConnection().close();??
????}??
public??void?delete()?throws?ClassNotFoundException,?SQLException?{??
//?定義sql語句??
String?sql1="delete?Table2?where?id='20121115'";??
String?sql2="delete?Table2?where?id='20121116'";??
//?3、創(chuàng)建語句對象??
????????st?=getConnection().createStatement();??
????????st.executeUpdate(sql1);??
????????st.executeUpdate(sql2);??
//?4、遍歷結(jié)果集:此處插入記錄不需要??
//?5、關(guān)閉資源對象??
?????????st.close();??
?????????getConnection().close();??
????}??
public?static?void?main(String[]?args)?throws?ClassNotFoundException,SQLException?{??
JDBCTest?jt=new?JDBCTest();??
????jt.add();??
????jt.update();??
????jt.delete();??
????}??
}??