最简单的jdbc

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



public class jidao {
	//驱动类的全名
	private static final 
		String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
	//链接的URL
	private static final 
		String URL="jdbc:sqlserver://localhost\\sqlexpress:1433;DatabaseName=zengshan";
	//登录sqlserver的用户名
	private static final
		String USERNAME="sa";
	//登录sqlserver的密码
	private static final
		String PWD="1234";
	//数据库对象声明
	
	private Connection con=null;
	private PreparedStatement pst=null;
	private ResultSet rs=null;
	
		
		/**
		 * 	加载驱动,建立连接	
		 */
		private void getConnection() throws ClassNotFoundException,
			SQLException {
				Class.forName(DRIVER);
					con=DriverManager.getConnection(URL,USERNAME,PWD);
}
		/**
		 * 执行查询   
		 * @param sql  执行的sql语句 
		 * @param params   Object数组,封装所有的Sql语句参数,顺序与sql语句参数一致
		 * @return   resultset  返回执行后的结果集
		 */
		public ResultSet execQuery(String sql,Object[] params){
			try {
				getConnection();
				pst=con.prepareStatement(sql);
				
				setPrepareStatementParams(params);
				rs=pst.executeQuery();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			return rs;
		}
		
		/**
		 * 执行增加,删除,修改SQL操作
		 * @param sql   执行的参数化SQL语句
		 * @param params   Object数组,封装所有的Sql语句参数,顺序与sql语句参数一致
		 * @return  int  受影响的行数,-1表示出现异常
		 */
		
		public int execUpdate(String sql,Object[] params){
			try {
				getConnection();
				pst=con.prepareStatement(sql);
				
				setPrepareStatementParams(params);
			int affectedRows=pst.executeUpdate();
			return affectedRows;
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (SQLException e) {
					e.printStackTrace();
				}finally{
					closeAll();
				}
				return -1;
		}

		/**
		 * 为PrepareStatementParams设置参数
		 * @param params   参数数组
		 * @throws SQLException   
		 */
		private void setPrepareStatementParams(Object[] params)
				throws SQLException {
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pst.setObject(i+1, params[i]);
				}
			}
		}

	/**
	 * 关闭connection,preparestatement,result
	 */
		//关闭数据库链接
		public void closeAll() {
		try{
				if(rs!=null){
					rs.close();
				}
				if(pst!=null){
					pst.close();
				}
				if(con!=null){
					con.close();
				}
			}catch(SQLException e){
				e.printStackTrace();
				
			}
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值