JDBC for MySQL的简单实用

来源:互联网 发布:rxjava源码分析 编辑:程序博客网 时间:2024/06/05 14:47

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