一、环境搭建
1、下载对应数据库连接驱动包并引入。
2、如果在web中调用必须在tomcat中也放入对应的驱动包。
3、在jre的lib\ext中也加入对应的驱动包。
二、连接数据库
public static  String server = "localhost";	//服务器
	public static String port = "1433";		//端口号
	public static String dbname = "testdb";	//数据库
	public static String user = "sa";		//用户名
	public static String pwd = "12345";		//用户密码
 
public static Connection createConnection() throws Exception{
        Connection conn = null;
        String url = "";
        try{
        	Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
        	url = "jdbc:sqlserver://" + server + ":" + port + ";DatabaseName=" + dbname; 
        	conn = DriverManager.getConnection(url,user,pwd); 
        }catch(SQLException sqlEx){      
        	throw sqlEx;
        }catch(Exception ex){       	
        	throw ex;
        }
        return conn;
    }
三、基本操作
1、插入:
Connection conn = createConnection();
			String sql = "insert into tmap (mapserviceid,mapid,mapname) values(?,?,?)";
			PreparedStatement pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, "1");
			pstmt.setString(2, "7");
			pstmt.setString(3, "test1");
			pstmt.executeUpdate();
			pstmt.close();
            conn.close();
2、查询
            String sql = "select * from tmap";
            PreparedStatement pstmt=conn.prepareStatement(sql);
            ResultSet rs=pstmt.executeQuery(); 
            while(rs.next()){
	     System.out.println(rs.getString("mapname"));
            }
3、更新
String sql = "update tmap set mapname=? where mapid = ?"; PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setString(1, "namename"); pstmt.setString(2, "7"); pstmt.executeUpdate();
4、删除
           String sql = "delete tmap where mapid = ?";
           PreparedStatement pstmt=conn.prepareStatement(sql);
           pstmt.setInt(1, 7);
           pstmt.executeUpdate();
原文:http://www.cnblogs.com/aegisada/p/4291938.html