package myBean;

import java.sql.*;

public class DBConnection {
	String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
	String sConnStr = "jdbc:odbc:userDB";
	
	//constructor
	public DBConnection() {
		try{
			Class.forName(sDBDriver);
		} catch(ClassNotFoundException e) {
			System.err.println("DBConnection(): " + e.getMessage());
		}
	}
	
	
	//用于执行查询数据库的操作
	//返回查询结果集
	public  ResultSet execQuery(String sql) {
		ResultSet rs=null;
		try {
			Connection conn = DriverManager.getConnection(sConnStr,"sa","1123");
			Statement stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			//stmt.close();
		} catch(SQLException ex) {
			System.err.println("DBConnection.execQuery(): " + ex.getMessage());
		}

		return rs;
	}
	
	
	//用于执行修改数据库的操作
	//返回受影响的行数
	public  int execModify(String sql) {
		int row_modified=0;
		try {
			Connection conn = DriverManager.getConnection(sConnStr,"sa","1123");
			Statement stmt = conn.createStatement();
			row_modified=stmt.executeUpdate(sql);
		} catch(SQLException ex) {
			System.err.println("DBConnection.execModify(): " + ex.getMessage());
		}
		
		return row_modified;
	}
	
	//用于处理汉字
	public String convertGBK(String str) {
		String strReturn="";
		try {
			strReturn=new String(str.getBytes("ISO-8859-1"),"GBK");
		} catch(Exception e) {
			System.err.println("DBConnection.convertGBK(): "+e.getMessage());
		}
		
		return strReturn;
	}
	
	//返回user表项数
	public int getCount() {
		ResultSet rs=null;
		int count=0;
		try {
			Connection conn = DriverManager.getConnection(sConnStr,"sa","1123");
			//Connection conn = DriverManager.getConnection(sConnStr);
			Statement stmt = conn.createStatement();
			rs = stmt.executeQuery("select count(id) from users");
			if(!rs.next()) {
				return 0;
			} else {
				count = rs.getInt(1);
			}
			stmt.close();
		} catch(Exception ex) {
			System.err.println("DBConnection.getCount(): " + ex.getMessage());
		}

		return count;
	}
	
	public String convertDB(String s) {

		StringBuffer str = new StringBuffer(s.length()<<1);
		for(int i=0; i<s.length(); ++i) {
			switch(s.charAt(i)) {
				case '\'':
					str.append("''");
					break;
				case '\"':
					str.append("\"\"");
					break;
				default:
					str.append(s.charAt(i));
					break;
			}
		}
		
		return str.toString();		
	}
	
/*	
	public static void main(String args[]){
		new DBConnection().getPageof("select name from user", "1", 3);
	}
*/
}