<<  < 2014 - >  >>
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31




package Dao;

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 BaseDao {
/**
* 获得数据库连接对象
* @return
*/
public static Connection getConn(){
Connection  conn=null;
String dburl="jdbc:mysql://localhost:3306/news";
String dbname="root";
String dbpwd="fengze";
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建连接
conn=DriverManager.getConnection(dburl,dbname,dbpwd);
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败!");
} catch (SQLException e) {
System.out.println("连接失败!");
}
return conn;
}
/**
* 通用的执行增删改操作的方法
* @param sql
* @param params 为?提供在参数值
* @return
*/
public static boolean excauteSQL(String sql,String[] params){
boolean flag=false;
//连接数据库
Connection conn=BaseDao.getConn();
PreparedStatement pst=null;
try {
//创建preparedStatement对象,并执行sql语句
pst=conn.prepareStatement(sql);
if(params!=null){
for(int i=0;i<params.length;i++){
pst.setString(i+1,params[i]);
}
}
//执行SQL语句
int result=pst.executeUpdate();
if(result>0){
flag=true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭连接
BaseDao.closeAll(conn, pst, null);
}
return flag;
}
/**
* 通用的执行关闭改操作的方法
* @param conn
* @param st
* @param rs
*/
public static void closeAll(Connection conn,Statement st,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

发表评论:
天涯博客欢迎您!