First, Environment construction
1, download the corresponding database connection driver package and introduce.
2, if the call in the Web must also be in Tomcat to put the corresponding driver package.
3. The corresponding driver package is also added to the lib\ext of the JRE.
Second, connect the database
public static string server = "localhost";//server public static string port = "1433";//port number public static string dbname = " TestDB ";//Database public static string user =" sa ";//user name public static string pwd =" 12345 ";//user password public static Connection Crea Teconnection () throws exception{ Connection conn = null; String url = ""; try{ class.forname ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); url = "jdbc:sqlserver://" + Server + ":" + Port + ";D atabasename=" + dbname; conn = Drivermanager.getconnection (URL,USER,PWD); } catch (SQLException Sqlex) { throw sqlex; } catch (Exception ex) { throw ex; } return conn; }
Three, the basic operation
1. Insert:
Connection conn = CreateConnection (); String sql = "INSERT into TMap (mapserviceid,mapid,mapname) VALUES (?,?,?)"; PreparedStatement pstmt=conn.preparestatement (SQL);p stmt.setstring (1, "1");p stmt.setstring (2, "7"); Pstmt.setstring (3, "Test1");p stmt.executeupdate ();p stmt.close (); Conn.close ();
2. Enquiry
String sql = "SELECT * from TMap"; PreparedStatement pstmt=conn.preparestatement (SQL); ResultSet rs=pstmt.executequery (); while (Rs.next ()) { System.out.println (rs.getstring ("mapname")); }
3. Update
String sql = "Update tmap set mapname=? " where mapid =? "; PreparedStatement pstmt=conn.preparestatement (SQL);p stmt.setstring (1, "NameName");p stmt.setstring (2, "7"); Pstmt.executeupdate ();
4. Delete
String sql = "Delete tmap where mapid =?"; PreparedStatement pstmt=conn.preparestatement (SQL); Pstmt.setint (1, 7); Pstmt.executeupdate ();
Basic Java Database Operations (SQL Server 2000 for example)