J#-封装数据库

package CSqlServer;

import java.sql.*;

//连接数据库封装类
public class ASql
{
    private Connection conn = null;
    private Statement st = null;
    private ResultSet rs = null;
    //连接数据库
    public ASql(String str)
    {
        try
        {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            String url = "jdbc:microsoft:sqlserver://PC-200908091543\\QZR;DatabaseName="+str;
            String user = "sa";
            String pwd = "";
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement(1004,1007);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    //执行insert、update、delete语句,返回受影响行数
    public int executeUpdate(String sql)
    {
        int row = 0;
        try
        {
            row = st.executeUpdate(sql);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return row;
    }
    //执行select查询,返回总记录数
    public int executeQuery(String sql)
    {
        int totalRow = 0;//总记录数
        try
        {
            rs = st.executeQuery(sql);
            rs.last();
            totalRow = rs.getRow();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return totalRow;
    }
    //定位游标
    public void setCurrentRow(int row)
    {
        try
        {
            rs.absolute(row);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    //获得某一字段值
    public String getString(String colName)
    {
        String value = null;
        try
        {
            value = rs.getString(colName);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return value;
    }
    //关闭数据库
    public void close()
    {
        try
        {
            if(rs != null)
                rs.close();
            if(st != null)
                st.close();
            if(conn != null)
                conn.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

 

posted on 2014-07-06 22:51  ylbtech  阅读(39)  评论(0)    收藏  举报