您的位置:首页 > 编程语言 > Java开发

eclipse中java操作mysql数据库注意事项

2011-08-14 17:13 447 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: