zoukankan      html  css  js  c++  java
  • java数据库基本操作(sqlserver 2000为例)

    一、环境搭建

    1、下载对应数据库连接驱动包并引入。

    2、如果在web中调用必须在tomcat中也放入对应的驱动包。

    3、在jre的libext中也加入对应的驱动包。

    二、连接数据库

    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();
    
    多看一行书,就少写一行代码,记录点滴,用心生活。
  • 相关阅读:
    bobobrowse为Lucene添加分组统计
    实现lucene检索结果排序
    facets in lucene
    lucene3.5 example
    Lucene聚类分组统计功能(grouping)
    Eclipse开发struts完全指南(三)实战
    缓存是什么?占内存吗?
    []利用memcached在多台服务器之间共享PHP的session数据
    HTML meta refresh 刷新与跳转(重定向)页面
    [置顶] 微信开发出现“该公众号暂时无法提供服务,请稍后再试”的坑
  • 原文地址:https://www.cnblogs.com/aegisada/p/4291938.html
Copyright © 2011-2022 走看看