eclipse中java操作mysql資料庫注意事項

來源:互聯網
上載者:User

1. 下載mysql JDBC驅動:例如mysql-connector-java-5.1.12(pudn上有);

2. 在eclipse裡的項目中建立lib目錄,把mysql-connector-java-5.1.12-bin-jar拷貝到這個目錄中,然後在項目的build path裡把這個jar包作為external jar加入到項目中;

3. import java.sql.*;
import com.mysql.jdbc.Driver;

4.測試

try {
         Class.forName("com.mysql.jdbc.Driver");  
         System.out.println("mysql驅動載入成功!");
        
         connect = DriverManager.getConnection("jdbc:mysql://localhost:6033/mslog","root","root");
         System.out.println("資料庫連接成功!");
            stmt = connect.createStatement(); /* -----建立statement對象,用於向資料庫發送sql語句-----   */
        
  }
     catch (Exception e) {
          System.out.print("mysql驅動載入失敗!");
          e.printStackTrace();
          return ;
     }
5. insert含變數時的sql語句的構造

String ipAddress=GetIpAdress(lineContent);
  String reqTime=GetReqTime(lineContent);
  String keyword=GetKeyword(lineContent,"keyword=");
  //String pageNum=GetPageNum(lineContent);
  String sourcePage=GetSourcePage(lineContent);
  String hitItem=GetHitItem(lineContent);
  String hitUrl=GetHitUrl(lineContent);
  
  String type=GetType(lineContent);
  
  if(type==null)
   type="0";
  
  String sqlStr="insert into hit(ipAddress,reqTime,keyword,sourcePage,hitItem,hitUrl,type) values("+"'"+ipAddress+"',"+"'"+reqTime+"',"+"'"+keyword+"',"+sourcePage+","+hitItem+","+"'"+hitUrl+"',"+type+")" ;//11,'北京','北京')";
  //String sqlStr="insert into hit(ipAddress,reqTime,keyword,sourcePage,hitItem,hitUrl,type) values('218.202.4.135','2011-08-11 00:00:00','女色網',3,8,'http://97.24644.com/',1)";
  
  System.out.println(sqlStr);
  insertDB(sqlStr);

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

  private void insertDB(String sqlStr)
    {
     if(stmt!=null)
     {
      //插入資料庫記錄
      try{
       stmt.executeUpdate(sqlStr);//.executeQuery(sqlStr);
      }
      catch(Exception e)
      {
        System.out.println("插入記錄失敗:"+sqlStr);
              e.printStackTrace();
      }
     }
    }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.