1. 程式人生 > >java如何連線與斷開SQL server2008資料庫

java如何連線與斷開SQL server2008資料庫

Connection con;
Statement stmt;

1.連線(返回0成功,返回1)

public  int Connect(String dbuserName,String dbpassword) 
	{
		
	String JDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";//SQL資料庫引擎
	String connectDB="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Songtest";//資料來源
	try
	{
	Class.forName(JDriver);//載入資料庫引擎,返回給定字串名的類
	}catch(ClassNotFoundException e)
	{
	return 1;
	} 
	try
	{
	String user=dbuserName;//使用者名稱
	String password=dbpassword;//使用者密碼
	Connection con=DriverManager.getConnection(co<pre name="code" class="java">
2.斷開(0成功,1失敗)
public  int closeConnect(){
	try {
		if(stmt!=null&&con!=null){//當連線存在,且命令物件存在
			stmt.close();//關閉命令物件連線
			con.close();//關閉資料庫連線
			return 0;
		}
		else if(con!=null&&stmt==null){//連線存在但命令物件不存在
		con.close();//關閉資料庫連線
		return 0;
		}else{//連線不存在的情況
			return 1;
		}
		
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return 1;
	}
		
	}