天天看點

Java 連接配接SQLserver

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Database

{ //資料庫連接配接方式是混合驗證方式

public String sqlserverDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String sql="select * from location";
Connection con = null;   //連接配接資料庫
Statement st = null;     //建立對象,用來執行不帶參數的SQL查詢和更新
PreparedStatement pre = null;//建立對象,用來執行帶參數的SQL語句
public ResultSet rs = null;//存放結果集

public  Connection getConnection() //建立對象的時候已經連接配接資料庫
{  
	try
	{
		Class.forName(sqlserverDriver);
		this.con = DriverManager.getConnection("jdbc:sqlserver://localhost:1434;"+"DatabaseName=user","sa","98515");
		this.st = this.con.createStatement();
		this.rs = st.executeQuery(sql);
		
	}
	catch(Exception e)
	{
		System.out.println(e.toString());
	}
	return con;
}

public ResultSet executeQuery(String strsql) //查詢記錄
{
	try 
	{
		this.rs = st.executeQuery(strsql);
		return rs;
	}
	catch(Exception e) 
	{
		e.printStackTrace();
		return null;
	}
}

public boolean execute(String strsql) //添加資料
{
	try 
	{
		if(this.st.executeUpdate(strsql) == 0)
			return false;
		else
			return true;
	}
	catch(SQLException e) 
	{
		e.printStackTrace();
		return false;
	}
}
           

}

繼續閱讀