package com.common;import java.util.*;
import java.sql.*;
import java.io.*; /**
  * auther caorj
  * @version 1.0
  */public class DbConnection
{    Connection conn  =null;
    Statement  stmt  =null;
    ResultSet  rset  =null;    public DbConnection(){}    public boolean openConnection()
    {
        java.util.Properties prop=new Properties();
        try{
            InputStream is=getClass().getResourceAsStream("/db.properties");
            prop.load(is);
            if(is!=null) is.close();
            String jdbc      =prop.getProperty("drivers");
            String url       =prop.getProperty("url");
            String user      =prop.getProperty("user");
            String password  =prop.getProperty("password");
            Class.forName(jdbc);
            this.conn=DriverManager.getConnection(url,user,password);
            is.close();
            is=null;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }    public ResultSet executeQuery(String query)  throws SQLException
    {
        this.stmt=conn.createStatement();
        this.rset=stmt.executeQuery(query);
        return rset;
    }    public void executeUpdate(String query)  throws SQLException
    {
        this.stmt   =conn.createStatement();
        int isdone=stmt.executeUpdate(query);
//        System.out.println(isdone+" record is updated!");
        if(stmt!=null) stmt.close();
    }    public void close() throws SQLException
    {
        if(conn!=null)conn.close();
        if(rset!=null)rset.close();
        if(stmt!=null)stmt.close();
    }    protected void finalize() throws Exception
    {
        this.close();
    }    public static void main(String[] arg)
    {
        try{
            DbConnection conn=new DbConnection();
            conn.openConnection();
            ResultSet rs=conn.executeQuery("select * from prod_target_1001");
            while (rs.next()){
                System.out.println("SesultSet getRow():"+rs.getRow());
//                System.out.println("getString:"+rs.getString("fieldName"));
            }
            conn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
}
}
文件db.properties中的内容(文件放在java代码包的最外层,在这里就是放在和com文件夹同级的目录中):
drivers=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://(机器名):1433;DatabaseName=(数据库名)
user=
password=

解决方案 »

  1.   

    to :littlecpu(可以包含中文字符)  我还没得非典> ^o^ 老师让我们用 vfq,我想用 java                             做,主要是学习java连接数据库!
    to : computerboy111(月亮) 这是 java 连接 sqlserver 的类么? 谢谢! 能再给点提示么?
      

  2.   

    楼上两个真是赤裸裸的流氓啊,哈哈。这个版的FAQ里边有很多Java连接数据库的例子,你去看一下吧。其中有连接sql的例子。
      

  3.   

    抱歉是连接sql server的例子。