eclipse中java操作mysql資料庫注意事項
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();
}
}
}