package com.xcgdt.template;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class BaseDao {
private static String drive_class = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=utf-8";
private static String user = "root";
private static String password = "shell_girl";
//加载驱动
static {
try {
Class.forName(drive_class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 连接数据库
*
* @param sql
* @return
*/
public Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 执行增删改
*
* @param sql
* @param pramas
* @return
*/
public ResultSet executeQuery(String sql, Object... pramas) {
Connection conn = this.getConnection();
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql);
if (pramas != null && pramas.length != 0) {
for (int i = 0; i < pramas.length; i++) {
stmt.setObject(i + 1, pramas[i]);
}
}
ResultSet rs = stmt.executeQuery();
return rs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 执行增删改
*
* @param sql
* @param pramas
* @return
*/
public int executeUpdate(String sql, Object... pramas) {
Connection conn = this.getConnection();
PreparedStatement pstmt = null;
try {
int result = 0;
pstmt = conn.prepareStatement(sql);
if (pramas != null && pramas.length != 0) {
for (int i = 0; i < pramas.length; i++) {
pstmt.setObject(i + 1, pramas[i]);
}
}
result = pstmt.executeUpdate();
return result;
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeAll(pstmt, null, conn);
}
return 0;
}
/**
* 释放资源
*
* @param stmt
* @param rs
* @param conn
*/
public void closeAll(Statement stmt, ResultSet rs, Connection conn) {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (rs != null) {
rs.close();
rs = null;
}
if (conn != null && conn.isClosed() == false) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}