⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbconnection.java

📁 新闻发布系统
💻 JAVA
字号:
package DBOperation;

import java.sql.*;


public class DBConnection {
	public Connection con;     //连接
	public Statement sta;      //语句块
	public PreparedStatement preSta;   //预处理语句块
	public ResultSet rs;     //结果集
	
	
	public String classStr;
	public String conStr;
	
	/**
	 * 指定所要操作的数据库名
	 */
	public DBConnection(String database) {
		classStr = "com.microsoft.jdbc.sqlserver.SQLServerDriver";      //加载驱动
		conStr = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName="+database;     //连接数据库
	}
	
	/**
	 *
	 * 带用户名与密码的连接
	 */
	public Connection getCon(String user,String pass) {
		if(this.con == null) {
			try {
				Class.forName(classStr);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
			try {
				this.con = DriverManager.getConnection(conStr,user,pass);
				this.sta = con.createStatement();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return this.con;
	}

	/**
	 *
	 * 默认连接
	 */
	public Connection getCon() {
		if(this.con == null) {
			try {
				Class.forName(classStr);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
			try {
				this.con = DriverManager.getConnection(conStr,"sa","");
				this.sta = con.createStatement();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return this.con;
	}
	
	/**
	 *
	 * 执行
	 */
	public boolean executeUpdate(String sql) {
		if(this.con == null) {
			this.getCon();
		}
		try {
			this.sta.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
		
	}

	/**
	 *
	 * 查询
	 */
	public ResultSet executeQuery(String sql) {
		if(this.con == null) {
			this.getCon();
		}
		try {
			this.rs= this.sta.executeQuery(sql);
			return this.rs;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 关闭连接
	 */
	public void Close() {
		try {
			this.rs.close();
		} catch(Exception ex) {
		}
		try {
			this.sta.close();
		} catch(Exception ex) {
		}
		try {
			this.preSta.close();
		} catch(Exception ex) {
		}
		try {
			this.con.close();
		} catch(Exception ex) {
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -