下面介紹一下連接Sqlserver數(shù)據(jù)庫。把連接Sqlserver數(shù)據(jù)庫封裝為一個(gè)方法,以便直接調(diào)用,而不需寫重復(fù)代碼。
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class sqlServer { ResultSet rs=null; //數(shù)據(jù)庫地址和數(shù)據(jù)庫名 String url="jdbc:sqlserver://localhost:1433;databaseName=Pet"; String DriverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; //數(shù)據(jù)庫名 String userName="sa"; //數(shù)據(jù)庫密碼 String passWord="123"; //建立數(shù)據(jù)庫連接方法 public Connection getConnection(){ //加載驅(qū)動(dòng) try { Class.forName(DriverClassName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.PRintStackTrace(); } Connection con =null; //獲取連接對(duì)象 try { con =DriverManager.getConnection(url,userName,password); System.out.println("數(shù)據(jù)庫連接成功!"); //連接數(shù)據(jù)庫 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } //======釋放資源方法=======public void ShiFang(ResultSet rs, Statement st,Connection con){ //如果結(jié)果集不為空,則釋放成功 ,否則失敗 try { if(rs!=null){ rs.close(); }if(st!=null){ st.close(); }if(con!=null){ con.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
新聞熱點(diǎn)
疑難解答
圖片精選