JDBC for MySQL的简单实用

JDBC 是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问。

首先需要创建一个操作类,用于连接MySQL。需要一个JDBC的jar包:mysql-connector-java-xxx-bin.jar

public class MySqlHelper {

      public static final String url = "jdbc:mysql://localhost:3306/zhouxiangyu";
      public static final String name = "com.mysql.jdbc.Driver";
      public static final String user = "root";
      public static final String password = "newpass";

      public Connection conn = null;
      public PreparedStatement pst = null;

      public MySqlHelper (String sql){
          try{
              Class.forName(name);
              conn = DriverManager.getConnection(url,user,password);
              pst = conn.prepareStatement(sql);
          }
          catch (Exception e){
               e.printStackTrace();
          }
      }
      public void close(){
          try {
           this.conn.close();
           this.pst.close();

          }catch (SQLException e){
              e.printStackTrace();
          }
    }
}
1.加载MySQL的驱动类

class.forName("com.mysql.jdbc.Driver");成功加载后会将Driver类的实例注册到DriverManager中。

2.连接MySQL数据库

  需要三个参数:数据库的url,数据库的 jdbc:mysql://lcoalhost:端口号/数据库名称

  数据库的用户名,和数据库的密码。

  最后获取连接Connection conn = DriverManager.getConnection(url, user,password);

3.创建statement对象用于将SQL语言发送到数据库中。statement实例分为以下3种类型:

 执行静态的SQL语句通常通过Statement实例实现。执行动态SQL语句通常通过PreparedStatement

实例实现。执行数据库存储过程通常通过CallableStatement实例实现。如果是第一种实现

Statement stmt = con。createStatement(); 如果是第二种实现PreparedStatement stmt = con.

prepareStatement(sql); CallableStatement stmt = con.prepareCall ("{CALL demoSp(?,?)}");

statement 接口提供了执行SQL语句的方法:executeQuery 用于查询SQL语句,executeUpdate 用于

实现插入,更新,删除的SQL语句。

4.执行SQL语句(以select username对应的password是否正确为例)

 在DaoImpl层中

static MySqlHelper db = null

public int queryPassword(String username,String password) throws SQLException {
    sql="select * from userInfo where username = '"+username+"'";
    db = new MySqlHelper(sql);
    int resultI = 0;
    ResultSet rs = null;
    try {
        rs=db.pst.executeQuery();
    }
    catch (SQLException e){
        e.printStackTrace();
    }
    while (rs.next()){
       if (!rs.getString("password").equals(password)){
           resultI=-1;
       }
    }
    return resultI;
}

ResultSet 为select的结果集,包含了符合SQL语句中条件的所有行,并且它通过一套get方法提供了

对这些行中数据的访问。

5.关闭JDBC

   需要关闭的对象为 Connection对象,Statement对象和ResultSet对象。

   Connection对象和Statement的对象关闭方法已经写到Helper中了,所以只需要MySqlHelper的close,再

   执行rs.close();即可。


demo地址:http://download.csdn.net/download/zhouxiangyu666666/9932962



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值