package com.guoyun.utils;
import java.sql.*;
/**
* ClassName:
* Function: ADD FUNCTION
* Reason: ADD REASON
*
* @author
* @Date
* @since Ver 1.1
*/
public class DBUtils {
//連接對象
public Connection conn;
//狀態對象
public Statement state;
//結果集合對象
public ResultSet rs;
//獲得數據庫的連接
public Connection getConnection(){
try {
//連接sqlserver
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root" ,"123");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//獲得數據庫狀態對象
public Statement getStatement(){
try {
state=getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return state;
}
//執行查詢sql語句的方法
public ResultSet query(String sql){
try {
rs=getStatement().executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//執行dml語言
public int update(String sql){
int result=-1;
try {
result=getStatement().executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeDB();
}
return result;
}
//關閉狀態對象 關閉數據庫連接
public void closeDB(){
try {
if(rs!=null){
rs.close();
}
if(state!=null){
state.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}