Java访问Sql Server 2008 数据库样例(完整例子)

备注:

     (1),文件列表

         

     (2) java访问sql server2008R2 设置 参考:

             java开发相关资料        http://blog.csdn.net/keenweiwei/article/details/7328611

     (3) 数据库 表结构

            

     (4)运行结果

                

     (5) 完整java代码下载: http://good.gd/1965614.htm

                (DBHelper 抄的人家的,自己改了一部份)

 

1.test1.java

import java.sql.ResultSet;
//import javax.swing.JOptionPane;

public class test11 {
	public static void main(String[] args) {
			DBHelper help=new DBHelper();
/*			if(help.TestConn())
				System.out.println("连接成功1");
			else
				System.out.println("连接失败1");*/
			
			//JOptionPane.showMessageDialog(null, "hello world");
			
			//String sSQL="select * from w_brand where id=? and brand_name =?";
			
			String sSQL="select * from w_brand where id=? and brand_name like '%{0}%'";
			sSQL=sSQL.replace("{0}", "柔");
			Object[] oParams=new Object[1];
			oParams[0]=5;
			//oParams[1]="柔";
			
/*			ResultSet rs=help.GetResultSet(sSQL, oParams);
			try
			{
				if(rs.next())
					System.out.println("id: " + rs.getString(1) + " brand_name: " + rs.getString(2));
					索引从1开始
			}catch(Exception ex)
			{
				System.out.println(ex.getMessage());
			}finally
			{
				try
				{
					rs.close();
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}*/
			
			Object oResult=help.GetSingle(sSQL, oParams);
			if(oResult!=null)
				System.out.println(oResult.toString());
			else
				System.out.println("没有符合条件的数据");
			
			//DataTable dt=help.GetDataTable(sSQL,oParams);
			
/*			String sSQL="select * from w_brand";
			DataTable dt=help.GetDataTable(sSQL);*/
			
/*			try
			{
				 int iRowCount = dt.RowCount;
				 int iColumnCount = dt.ColumnCount;
				 System.out.println("行数:" + iRowCount + ",列数:" + iColumnCount);
				 DataTable.PrintTable(dt);
				 //rs.last();
				//System.out.println("数据行:" + rs.getRow());
			}catch(Exception ex)
			{
				System.out.println("错误提示:" + ex.getMessage());
			}*/
 
	}
}

 

2.DBHelper.java

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import com.microsoft.sqlserver.jdbc.*;

public class DBHelper {
	Connection _CONN = null;
	
	//取得连接
	private boolean GetConn(String sUser, String sPwd) {
		if(_CONN!=null)return true;
		try {			
			String sDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
			// String sDBUrl ="jdbc:sqlserver://192.168.0.74;databaseName=wakeup";
			String sDBUrl = "jdbc:sqlserver://192.168.2.28\\JONSE;databaseName=wakeup";

			Class.forName(sDriverName);
			_CONN = DriverManager.getConnection(sDBUrl, sUser, sPwd);

		} catch (Exception ex) {
			// ex.printStackTrace();
			System.out.println(ex.getMessage());
			return false;
		}
		return true;
	}
	
	private boolean GetConn()
	{
		return GetConn("sa","aaaaaa");
	}
	
	//关闭连接
	private void CloseConn()
	{
		try {
			_CONN.close();
			_CONN = null;
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			_CONN=null;	
		}
	}
 
	
	//测试连接
	public boolean TestConn() {
		if (!GetConn())
			return false;

		CloseConn();
		return true;
	}
	
	public ResultSet GetResultSet(String sSQL,Object[] objParams)
	{
		GetConn();
		ResultSet rs=null;
		try
		{
			PreparedStatement ps = _CONN.prepareStatement(sSQL);
			if(objParams!=null)
			{
				for(int i=0;i< objParams.length;i++)
				{
					ps.setObject(i+1, objParams[i]);
				}
			}
			rs=ps.executeQuery();
		}catch(Exception ex)
		{
			System.out.println(ex.getMessage());
			CloseConn();
		}
		finally
		{
			//CloseConn();			
		}
		return rs;
	}
	
	public Object GetSingle(String sSQL,Object... objParams)
	{
		GetConn();
		try
		{
			PreparedStatement ps = _CONN.prepareStatement(sSQL);
			if(objParams!=null)
			{
				for(int i=0;i< objParams.length;i++)
				{
					ps.setObject(i+1, objParams[i]);
				}
			}
			ResultSet rs=ps.executeQuery();
			if(rs.next())
				return rs.getString(1);//索引从1开始
		}catch(Exception ex)
		{
			System.out.println(ex.getMessage());
		}
		finally
		{
			CloseConn();			
		}
		return null;
	}
	
	public DataTable GetDataTable(String sSQL,Object... objParams)
	{
		GetConn();
		DataTable dt=null;
		try
		{
			PreparedStatement ps = _CONN.prepareStatement(sSQL);
			if(objParams!=null)
			{
				for(int i=0;i< objParams.length;i++)
				{
					ps.setObject(i+1, objParams[i]);
				}
			}
			ResultSet rs=ps.executeQuery();
			ResultSetMetaData rsmd=rs.getMetaData();
			
			List<DataRow> row=new ArrayList<DataRow>(); //表所有行集合
			List<DataColumn> col=null; //行所有列集合
			DataRow r=null;// 单独一行
			DataColumn c=null;//单独一列
			
			String columnName;
			Object value;
			int iRowCount=0;
			while(rs.next())//开始循环读取,每次往表中插入一行记录
			{
				iRowCount++;
				col=new ArrayList<DataColumn>();//初始化列集合
				for(int i=1;i<=rsmd.getColumnCount();i++)
				{
					columnName=rsmd.getColumnName(i);
					value=rs.getObject(columnName);
					c=new DataColumn(columnName,value);//初始化单元列
					col.add(c); //将列信息加入到列集合
				}
				r=new DataRow(col);//初始化单元行
				row.add(r);//将行信息加入到行集合
			}
			dt = new DataTable(row);
			dt.RowCount=iRowCount;
			dt.ColumnCount = rsmd.getColumnCount();
		}catch(Exception ex)
		{
			System.out.println(ex.getMessage());
		}
		finally
		{
			CloseConn();			
		}
		return dt;
	}
	
	public int UpdateData(String sSQL,Object[] objParams)
	{
		GetConn();
		int iResult=0;
		
		try
		{
			PreparedStatement ps = _CONN.prepareStatement(sSQL);
			if(objParams!=null)
			{
				for(int i=0;i< objParams.length;i++)
				{
					ps.setObject(i+1, objParams[i]);
				}
			}
			iResult = ps.executeUpdate(sSQL);
		}catch(Exception ex)
		{
			System.out.println(ex.getMessage());
			return -1;
		}
		finally
		{
			CloseConn();			
		}
		return iResult;
	}
	
	

}


3, DataTable.java

import java.util.List;
//import java.util.ArrayList;

public class DataTable {
	List<DataRow> row;
	public DataTable(){}
	public DataTable(List<DataRow> _row)
	
	public List<DataRow> GetRow()
	{
		return row;
	}
	
	public void SetRow(List<DataRow> _row)
	{
		row = _row;
	}
 
    public static void PrintTable(DataTable dt) { 
        for (DataRow r : dt.GetRow()) { 
            for (DataColumn c : r.GetColumn()) { 
                System.out.print(c.GetKey() + ":" + c.GetValue() + "  "); 
            } 
            System.out.println(""); 
        } 
    } 
    
    public static int RowCount=0;
    public static int ColumnCount=0;
}

4.DataRow.java

import java.sql.Date;
import java.sql.Blob;
import java.util.List;


public class DataRow {
	List<DataColumn> col;
	public DataRow(List<DataColumn> _col)
	{
		col = _col;
	}
	
	public List<DataColumn> GetColumn()
	{
		return col;
	}
	
	public void SetColumn(List<DataColumn> _col)
	{
		col = _col;
	}
	
	public DataColumn GetColumn(String colName)
	{
		for(DataColumn c:col)
		{
			if(c.GetKey().toUpperCase().equals(colName.toUpperCase()))
			{
				try
				{
					return c;
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}
		}
		
		return null;
	}
	
	public int GetColumnInt(String colName)
	{
		for(DataColumn c:col)
		{
			if(c.GetKey().toUpperCase().equals(colName.toUpperCase()))
			{
				try
				{
					return Integer.parseInt(c.GetValue().toString());
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}
		}
		
		return 0;
	}
	
	public String GetColumnString(String colName)
	{
		for(DataColumn c:col)
		{
			if(c.GetKey().toUpperCase().equals(colName.toUpperCase()))
			{
				try
				{
					return c.GetValue().toString();
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}
		}
		
		return "";
	}
	
	public Date GetColumnDate(String colName)
	{
		for(DataColumn c:col)
		{
			if(c.GetKey().toUpperCase().equals(colName.toUpperCase()))
			{
				try
				{
					return Date.valueOf(c.GetValue().toString());
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}
		}
		
		return null;
	}
	
	public Blob GetColumnBlob(String colName)
	{
		for(DataColumn c:col)
		{
			if(c.GetKey().toUpperCase().equals(colName.toUpperCase()))
			{
				try
				{
					return (Blob)c.GetValue();
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}
		}
		
		return null;
	}
	
	public float GetColumnFloat(String colName)
	{
		for(DataColumn c:col)
		{
			if(c.GetKey().toUpperCase().equals(colName.toUpperCase()))
			{
				try
				{
					return Float.parseFloat(c.GetValue().toString());
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
				}
			}
		}
		
		return 0;
	}
	
}

5.DataColumn.java

public class DataColumn {
	String key;
	Object value;
	
	public DataColumn(String _key,Object _value)
	{
		key = _key;
		value = _value;
	}
	
	public String GetKey()
	{
		return key;
	}
	
	public Object GetValue()
	{
		return value;
	}
	
	public void SetKey(String _key)
	{
		key = _key;
	}
	
	public void SetValue(Object _value)
	{
		value = _value;
	}
}


 

  • 13
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值