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 DBConnection {
public static Connection getConn() {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String user = "";
String password = "";
String dbName = "";
Connection con = null;
String url = "jdbc:sqlserver:/**********:1433;databaseName=" + dbName;
try {
Class.forName(driverName).newInstance();
System.out.println("*******開始進行連線********");
con = DriverManager.getConnection(url,user,password);
System.out.println("********連線資料庫成功!***\n");
} catch (Exception e) {
System.err.println("連線資料庫不成功");
e.printStackTrace();
}
return con;
}
/**
* 關閉連線
*
* @param conn
* @param pre
* @param rs
*/
public static void closeConn(ResultSet rs,PreparedStatement pre,Connection conn) {
try {
if (conn != null)
conn.close();
if (pre != null)
pre.close();
if (rs != null)
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
/*try {
System.out.println("測試資料庫連線開始\n");
Connection conn=DBConnection.getConn();
String sql1="select * from dbo.Se";
PreparedStatement pre = conn.prepareStatement(sql1);
ResultSet rs=pre.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
}
System.out.println("測試資料庫連線結束");
DBConnection.close(conn, pre, rs);
} catch (Exception e) {
e.printStackTrace();
}*/
}
}