2020.03.23 idea中數據庫的連接


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();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM