DBHelper.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DBHelper {
public static final String url="jdbc:mysql://数据库地址";
public static final String name="com.mysql.jdbc.Driver";
public static final String user="数据库用户名";
public static final String password="数据库密码";
public Connection conn=null;
public PreparedStatement pst = null;
public DBHelper(String sql)
{
try {
Class.forName(name);
conn=DriverManager.getConnection(url,user,password);
pst=conn.prepareStatement(sql);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void close()
{
try {
this.conn.close();
this.pst.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
实例:
import java.sql.ResultSet;
public class Ten_tuijian {
static String sql=null;
static DBHelper db1=null;
static ResultSet res=null;
/**
* @param args
* 获取10件商品
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sql="select goods_id,title,price_string,pic_url,parent_market_name,store_num from goods_hz limit 0,10";
db1=new DBHelper(sql);
try {
res=db1.pst.executeQuery();
while(res.next())
{
String goodsId=res.getString(1);
String title=res.getString(2);
String price=res.getString(3);
String picUrl=res.getString(4);
String parentName=res.getString(5);
if(parentName.equals("置地国际电商基地"))
{
//System.out.println(1111111);
parentName=parentName.replace("置地国际", "");
}
String storeNum=res.getString(6);
System.out.println("<li><a href='http://hz.571xz.com/item.htm?id="+goodsId+"'><img src='"+picUrl+"_220x220.jpg' style='width:180px;'><h2>¥ "+
price+"<span>"+parentName+storeNum+"</span></h2><p>"+title+"</p></a></li>");
}
res.close();
db1.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
别忘了导入Connector/J包,下载地址http://www.mysql.com/downloads/connector/j/