標籤:
一、環境搭建
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為例)