丄諦啲仇魜ヤ
          如 果 敵 人 讓 你 生 氣 , 那 說 明 你 沒 有 勝 他 的 把 握!
          posts - 6,comments - 56,trackbacks - 1

           

          ///幾個重要的語句
          String insertSql="insert into Product(name,price) values('"+name+"',"+price+")";//price 為整型
          String updateSql="update Product set  PName='"+name+"', PPrice="+price+" where PID='"+id+"'";
          String sql="select * from Product where PName like '%"+key+"%'";
          String sql = "delete  t_user  where userid="+userid;

          JNDI方法一
          /////////////////////////////////////////
          記得導入6個.JAR包并在tomcat中的lib文件下也要導入這6個.JAR包
          工具類

          package util;

          import java.sql.Connection;
          import java.sql.PreparedStatement;
          import java.sql.ResultSet;
          import java.sql.ResultSetMetaData;
          import java.sql.SQLException;
          import java.sql.Statement;
          import java.util.ArrayList;
          import javax.naming.Context;
          import javax.naming.InitialContext;
          import javax.sql.DataSource;

          import com.Admin;

          /**
           * @author wsq
           * @version 1.0 07/10/20
           */
          public class DBConnection {

           private static Connection con = null;

           private static Statement stmt = null;

           private static ResultSet rs = null;

           private static ArrayList<String[]> ArrayRs = null;

           /**
            *
            * 創建數據源
            *
            * @return Connection
            * @throws Exception
            */
           public static synchronized Connection getConnection() throws Exception {
            Context initCtx = new InitialContext(); // 從Context中lookup數據源。
            DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/data"); // jdbc/data為下面Resource的name屬性
            return ds.getConnection();
           }

           /**
            *
            * 執行數據查詢操作
            *
            * @param sql
            * @return ResultSet
            */
           public static ArrayList executeQuery(String sql) {
            try {
             stmt = con.createStatement();
             rs = stmt.executeQuery(sql);
             ResultSetMetaData rsmd = rs.getMetaData(); // 獲取此 ResultSet 對象的列的編號、類型和屬性。
                    
             int numberOfColumns = rsmd.getColumnCount();// 返回此 ResultSetMetaData對象中的列數。
                        

             // 判斷是否為空
             if (!ArrayRs.isEmpty()) {
              ArrayRs.clear();
             }
             /*
              * 將每條記錄寫入數組 將數組放在ArrayList里
              */
             while (rs.next()) {
              String[] strArrayTemp = new String[numberOfColumns];
              for (int i = 0; i < numberOfColumns; i++) {
               if (rs.getObject(i + 1) == null) {
                strArrayTemp[i] = "";
               } else {
                strArrayTemp[i] = rs.getObject(i + 1).toString();// 以
                      // Java
                      // 編程語言中
                      // Object
                            // 的形式獲取此
                            // ResultSet
                           // 對象的當前行中指定列的值;
                       // 第一個列是1,第二個列是2,....
                            
                System.out.println(" test value    " + strArrayTemp[i]);

               }
              }
              ArrayRs.add(strArrayTemp);
             }
             System.out.println("executeQuery successfully!");

             return (ArrayList) ArrayRs.clone();
            } catch (SQLException ex) {
             System.out.println("query error:" + ex.getMessage());
            } finally {
             DBConnection.close();
            }
            return ArrayRs;
           }

           /**
            * @param executeInsert插入數據方法
            * @return 插入條數是否成功(boolean)
            */
           public static boolean executeInsert(String strSql) throws SQLException {
            rs = null;
            try {
             con = DBConnection.getConnection();
             stmt = con.createStatement();
             con.setAutoCommit(true);
             int i = stmt.executeUpdate(strSql);

             if (i == 1) {
              return (true);
             }
            } catch (Exception e) {
             System.out.println("Insert error:" + e.getMessage());
            } finally {
             DBConnection.close();
            }

            return (false);
           }

           /**
            * 執行數據更新操作
            *
            * @param sql
            * @return 更新是否成功 (int)
            * @throws Exception
            */
           public static int executeUpdate(String sql) throws Exception {
            int result = 0;
            con = DBConnection.getConnection();
            try {
             Statement stmt = con.createStatement();
             result = stmt.executeUpdate(sql);// 返回影響的行數
             con.commit(); // 提交

            } catch (SQLException ex) {
             try {
              con.rollback();// 回滾
             } catch (SQLException e) {
              System.out.println("update error:" + e.getMessage());
             }
             System.err.println(ex.getMessage());

            } finally {
             DBConnection.close();
            }
            return result;
           }

           /**
            * @param executeDelete刪除數據方法
            * @return 刪除數據數(int)
            */
           public static int executeDelete(String strSql) throws SQLException {
            rs = null;
            int j = 0;
            try {
             con = DBConnection.getConnection();
             stmt = con.createStatement();
             con.setAutoCommit(false);
             j = stmt.executeUpdate(strSql);

             if (j > 0) {
              con.commit();
             } else {
              con.rollback();
             }
            } catch (Exception e) {
             System.out.println("Delete error:" + e.getMessage());
            } finally {
             DBConnection.close();
            }
            return j;
           }

           /**
            *
            * 關閉連接,將連接送回連接池
            *
            */

           public static void close() {
            if (con != null) {
             try {
              con.close();
              con = null;
             } catch (SQLException ex) {
              System.err.println(ex.getMessage());
             }
            }
           }

          }

          在項目的...\WebRoot\META-INF下創建個context.xml或者在tomcat中的server.xml寫
            <Context path="/jndi" docBase="jndi" debug="0"  reloadable="true" crossContext="true">   
             <Resource name="jdbc/data"  auth="Container" type="javax.sql.DataSource"     
                        driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
                        url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=dbs"        
                        username="wsq" password="123"   maxIdle="20" maxWait="5000"   
                        maxActive="100" removeAbandoned="true"
              removeAbandonedTimeout="60" logAbandoned="true"/>
          </Context>

           

          方法二
          Struts(1.2)
          /////////////////////////
          連接池在struts-cionfig.xml中的配置(sql2000)
           <data-sources>
              <data-source type="org.apache.commons.dbcp.BasicDataSource" key="data'>
                <set-property property="driverClassName"value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />//記得要Name
           <set-property property="url"value="jdbc:microsoft:sqlserver://localhost:1433;databasename=dbs" />
           <set-property property="username" value="wsq" />//記得要name
           <set-property property="password" value="123" />
           <set-property property="maxActive" value="10" />
           <set-property property="maxWait" value="5000" />
           <set-property property="defaultAutoCommit" value="false" />//記得在false的情況(插入和更新時要con.commit)
           <set-property property="defaultReadOnly" value="false" />
             </data-source>
          </data-sources>
          /////////////////////////////////////////////////////////
                                輔助類
          package tools;

          import java.sql.Connection;
          import java.sql.ResultSet;
          import java.sql.SQLException;
          import java.sql.Statement;

          import javax.sql.DataSource;

          public class DBUtil {
           Connection con=null;
           ResultSet rs = null;
           
           public DBUtil(DataSource dataSource)
           {
            try {
             con=dataSource.getConnection();
            } catch (SQLException e) {
             
             e.printStackTrace();
            }
           }
          ////在數據庫中執行查詢操作
           public ResultSet executeQuery(String sql) {
            try {
             Statement stmt = con.createStatement();
             rs = stmt.executeQuery(sql);
            }
            catch(SQLException ex) {
             ex.printStackTrace();
            }
            return rs;
           }
          // 在數據庫中執行數據更新的方法
           public int executeUpdate(String sql) {
            int result = 0;
            try {
             Statement stmt = con.createStatement();
             
             //返回影響的行數
             result = stmt.executeUpdate(sql);
            }
            catch(SQLException ex) {
             try {
              con.rollback();                       //回滾
             } catch (SQLException e) {
              // TODO 自動生成 catch 塊
              e.printStackTrace();
             }
             System.err.println(ex.getMessage());
             
            }
            return result;
           }
          // 關閉數據源
           public void close(){
            if(con!=null){
             try{
              con.close();
              con = null; 
             }catch(SQLException ex) {
              System.err.println(ex.getMessage());
             }
            } 
           }

          }
          //////////////////////////////////////////////////////////////////////////////////////
                                (不利用輔助類時)
          在xxxAction.java中的execute()方法中
            try{
                DataSource dataSource=getDataSource(request,"data");//得到數據源
                                           //得到數據源ServletContext context=servlet.getServletContext();
                                           // DataSource dataSource=(DataSource) context.getAttribute("data");
                Connetion con=dataSource.getConnection();
                PreparedStatement pstm=con.prepareStatement("insert into userone (name,password) values(?,?)");
                pstm.setString(1,name);
                pstm.setString(2,password);
                pstm.executUpadate();
                con.commit();/////記得寫上(在插入或更新時一定要記得加上)正確是提交事務
                } catch (SQLException e) {
              con.rollback();//失敗時回滾
              e.printStackTrace();
             }
             
             finally{
              pstm.close();
              con.close();

           

                }


          方法三(最原始的)直接連
          **********************
          1. MySQL(http://www.mysql.com)mm.mysql-2.0.2-bin.jar/
          Class.forName( "org.gjt.mm.mysql.Driver" );
          cn = DriverManager.getConnection(
          "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", sUsr, sPwd );

          2. PostgreSQL(http://www.de.postgresql.org)pgjdbc2.jar/
          Class.forName( "org.postgresql.Driver" );
          cn = DriverManager.getConnection(
          "jdbc:postgresql://MyDbComputerNameOrIP/myDatabaseName", sUsr, sPwd );

          3. Oracle(http://www.oracle.com/ip/deploy/database/oracle9i/)classes12.zip
          Class.forName( "oracle.jdbc.driver.OracleDriver" );
          cn = DriverManager.getConnection(
          "jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:ORCL", sUsr, sPwd );

          4. Sybase(http://jtds.sourceforge.net)jconn2.jar/
          Class.forName( "com.sybase.jdbc2.jdbc.SybDriver" );
          cn = DriverManager.getConnection(
          "jdbc:sybase:Tds:MyDbComputerNameOrIP:2638", sUsr, sPwd );
          //(Default-Username/Password: "dba"/"sql")

          5. Microsoft SQLServer(http://jtds.sourceforge.net/)
          Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
          cn = DriverManager.getConnection(
          "jdbc:jtds:sqlserver://MyDbComputerNameOrIP:1433/master", sUsr, sPwd );

          6. Microsoft SQLServer(http://www.microsoft.com/)
          Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
          cn = DriverManager.getConnection(
          "jdbc:microsoft:sqlserver://localhost:1433;databaseName=dbs", sUsr, sPwd );

          7. ODBC
          Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
          Connection cn = DriverManager.getConnection( "jdbc:odbc:" + sDsn, sUsr, sPwd
          );

           

           
          select @@version 是查看你的MSSQL版本  看補丁打沒打
          ///////////////////////////////////////////////////////////////////////////////////


          String insertSql="insert into Product values('"+id+"','"+name+"',"+price+")";
          String updateSql="update Product set  PName='"+name+"', PPrice="+price+" where PID='"+id+"'";
          String sql="select * from Product where PName like '%"+key+"%'";
          String sql = "delete  t_user  where userid="+userid;


          ////////////////////////////////////////////////////////
           

           
           

          posted on 2007-09-22 13:40 Crying 閱讀(850) 評論(0)  編輯  收藏 所屬分類: 數據庫
          主站蜘蛛池模板: 双牌县| 吉隆县| 文成县| 林口县| 新晃| 泗水县| 年辖:市辖区| 博乐市| 宜宾市| 成都市| 巫山县| 岳西县| 上虞市| 沁水县| 德令哈市| 班戈县| 通化市| 怀仁县| 隆回县| 雅江县| 宁武县| 缙云县| 澄城县| 铁力市| 娄底市| 新宁县| 巴塘县| 青龙| 巴林右旗| 佳木斯市| 高陵县| 弥渡县| 凤山市| 黎平县| 赤壁市| 湖南省| 揭东县| 宜兴市| 论坛| 靖州| 济阳县|