java資料庫基本操作(sqlserver 2000為例)

來源:互聯網
上載者:User

標籤:

一、環境搭建

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();

 

java資料庫基本操作(sqlserver 2000為例)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.