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

           

          ///幾個(gè)重要的語(yǔ)句
          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方法一
          /////////////////////////////////////////
          記得導(dǎo)入6個(gè).JAR包并在tomcat中的lib文件下也要導(dǎo)入這6個(gè).JAR包
          工具類(lèi)

          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;

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

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

             // 判斷是否為空
             if (!ArrayRs.isEmpty()) {
              ArrayRs.clear();
             }
             /*
              * 將每條記錄寫(xiě)入數(shù)組 將數(shù)組放在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
                      // 編程語(yǔ)言中
                      // Object
                            // 的形式獲取此
                            // ResultSet
                           // 對(duì)象的當(dāng)前行中指定列的值;
                       // 第一個(gè)列是1,第二個(gè)列是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插入數(shù)據(jù)方法
            * @return 插入條數(shù)是否成功(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);
           }

           /**
            * 執(zhí)行數(shù)據(jù)更新操作
            *
            * @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);// 返回影響的行數(shù)
             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刪除數(shù)據(jù)方法
            * @return 刪除數(shù)據(jù)數(shù)(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;
           }

           /**
            *
            * 關(guān)閉連接,將連接送回連接池
            *
            */

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

          }

          在項(xiàng)目的...\WebRoot\META-INF下創(chuàng)建個(gè)context.xml或者在tomcat中的server.xml寫(xiě)
            <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的情況(插入和更新時(shí)要con.commit)
           <set-property property="defaultReadOnly" value="false" />
             </data-source>
          </data-sources>
          /////////////////////////////////////////////////////////
                                輔助類(lèi)
          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();
            }
           }
          ////在數(shù)據(jù)庫(kù)中執(zhí)行查詢操作
           public ResultSet executeQuery(String sql) {
            try {
             Statement stmt = con.createStatement();
             rs = stmt.executeQuery(sql);
            }
            catch(SQLException ex) {
             ex.printStackTrace();
            }
            return rs;
           }
          // 在數(shù)據(jù)庫(kù)中執(zhí)行數(shù)據(jù)更新的方法
           public int executeUpdate(String sql) {
            int result = 0;
            try {
             Statement stmt = con.createStatement();
             
             //返回影響的行數(shù)
             result = stmt.executeUpdate(sql);
            }
            catch(SQLException ex) {
             try {
              con.rollback();                       //回滾
             } catch (SQLException e) {
              // TODO 自動(dòng)生成 catch 塊
              e.printStackTrace();
             }
             System.err.println(ex.getMessage());
             
            }
            return result;
           }
          // 關(guān)閉數(shù)據(jù)源
           public void close(){
            if(con!=null){
             try{
              con.close();
              con = null; 
             }catch(SQLException ex) {
              System.err.println(ex.getMessage());
             }
            } 
           }

          }
          //////////////////////////////////////////////////////////////////////////////////////
                                (不利用輔助類(lèi)時(shí))
          在xxxAction.java中的execute()方法中
            try{
                DataSource dataSource=getDataSource(request,"data");//得到數(shù)據(jù)源
                                           //得到數(shù)據(jù)源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();/////記得寫(xiě)上(在插入或更新時(shí)一定要記得加上)正確是提交事務(wù)
                } catch (SQLException e) {
              con.rollback();//失敗時(shí)回滾
              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版本  看補(bǔ)丁打沒(méi)打
          ///////////////////////////////////////////////////////////////////////////////////


          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 閱讀(849) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): 數(shù)據(jù)庫(kù)
          主站蜘蛛池模板: 镇安县| 西城区| 剑川县| 巩留县| 和林格尔县| 那曲县| 远安县| 土默特右旗| 错那县| 花莲市| 陵水| 屏东市| 五大连池市| 湘阴县| 清丰县| 太康县| 奉化市| 林甸县| 巴彦县| 晋州市| 鄂托克前旗| 黄陵县| 金门县| 临高县| 铜陵市| 荃湾区| 阳新县| 保山市| 耒阳市| 凌源市| 荆门市| 镇宁| 五峰| 容城县| 武清区| 海兴县| 福海县| 富民县| 龙川县| 保德县| 清水河县|