BaseDao


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BaseDao {

	public Connection getConn() { // 获取数据库连接方法
		try {
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("注册驱动异常");
			e.printStackTrace();
		}
		Connection conn = null;
		String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=sjk1";
		try {
			conn = DriverManager.getConnection(url, "sa", "123");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("连接数据库异常");
			e.printStackTrace();
		}
		return conn;
	}

	/* 关闭资源方法 */
	public void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("RS关闭发生异常");
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("pstmt关闭发生异常");
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("conn关闭发生异常");
				e.printStackTrace();
			}
		}
	}

	public int executeSQL(String sql, String[] getValue) {
		int result = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = getConn(); // 获取数据库连接方法
			pstmt = conn.prepareStatement(sql);
			if (getValue != null) {
				for (int i = 0; i < getValue.length; i++) {
					pstmt.setString(i + 1, getValue[i]);
				}
			}
			result = pstmt.executeUpdate(); // 执行SQL语句
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("executeSQL方法异常");
			e.printStackTrace();
		} finally {
			closeAll(conn, pstmt, null);
		}
		return result;
	}
}

你可能感兴趣的:(seda)