JAVA使用JDBC连接MySQL数据库

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值