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

📄 dbwork.java

📁 IO流的项目好
💻 JAVA
字号:
//数据库操作
package myQQ;

import java.sql.*;
import java.util.*;

class DBWork
{
	/*
	String DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
	String url = "jdbc:odbc:QQ";	
	*/
	
	String DBDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
	String url = "jdbc:microsoft:sqlserver://127.0.0.1:1433";
	
	String username; //用户名
	String pw; //密码
	Connection con = null; //联接
	Statement stmt = null; //中间载体
	PreparedStatement pstmt = null; //传入参数中间载体
	CallableStatement cstmt = null; //调用存储过程中间载体
	ResultSet rt = null; //结果集
	ResultSetMetaData rtmd = null; //元数据
	Vector vData = new Vector(); //返回结果的二维集合
	Vector vCell;
	
	DBWork(String username,String pw)
	{
		this.username = username;
		this.pw = pw;	
	}
	
	public void setCon(int type) throws Exception
	{
		//加载驱动程序
		Class.forName(this.DBDriver);
		//建立连接
		con = DriverManager.getConnection(this.url,this.username,this.pw);
		//创建中间载体
		if(type==0)
			stmt = con.createStatement();
	}
	
	public void closeCon(int type) throws Exception
	{
		//关闭中间载体及连接 
		if(type==0)
			stmt.close(); 
		else if(type==1)
			pstmt.close();
		else
			cstmt.close();
		con.close();	
	}
	
	public boolean exe(String sql)
	{	//执行查询外的语句
		boolean f = false;
		try {
			this.setCon(0);
			//执行sql语句
			stmt.execute(sql);
			this.closeCon(0);
			f = true;	
	    }
	    catch (Exception ex) {
	    	System.out.println (ex);
	    }
	    return f;
	}
	
	public Vector exeQuery(String sql)
	{	//查询--不调用存储过程
		try {
			this.setCon(0);
			//执行spl语句
			rt = stmt.executeQuery(sql);
			this.setData(); //设置所取得的数据
			rt.close();
	    	this.closeCon(0);		
	    }
	    catch (Exception ex) {
	    	System.out.println (ex);
	    }
	    return vData;
	}
	
	public boolean Pexe(String sql,Object[] o)
	{	//利用PreparedStatement执行sql语句
		boolean f = false;
		try {
			this.setCon(1);
			pstmt = con.prepareCall(sql); //建立参数中间载体
			for (int i = 1; i<=o.length; i++)
			{
				pstmt.setObject(i,o[i-1]); //设置参数
			}
			pstmt.executeUpdate(); //执行插入、修改、删除语句
			this.closeCon(1);
			f = true;
	    }
	    catch (Exception ex) {
	    	System.out.println (ex);
	    }
	    return f;
	}
	
	public Vector exePro(String pro)
	{	//调用存储过程
		try {
			this.setCon(2);
			//执行spl语句
			cstmt = con.prepareCall("{call "+pro+"}");
			rt = cstmt.executeQuery();
			this.setData(); //设置所取得的数据
			rt.close();
	    	this.closeCon(2);		
	    }
	    catch (Exception ex) {
	    	System.out.println (ex);
	    }
	    return vData;
	}
	
	public void setData() throws Exception
	{	//设置所取得的数据
		//获得元数据
		rtmd = rt.getMetaData();
		//获得列数
		int c = rtmd.getColumnCount();
		vData.clear(); //预先清空
		while(rt.next())
		{
			vCell = new Vector();
			for (int i = 1; i<=c; i++)
			{
				vCell.addElement(rt.getString(i));
			}
			vData.addElement(vCell);
		}
	}
}

⌨️ 快捷键说明

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