jdbc

来源:互联网 发布:淘宝的被子能买吗 编辑:程序博客网 时间:2024/06/07 01:24
   jdbc使用分为五个步骤

一:注册驱动
二:建立与数据库的连接,获得连接对象
三:根据连接对象,获得一个对象
四:根据获得的对象执行SQL语句
五:释放资源(关流)

一:注册驱动

DriverManager.registerDriver(new Driver());//因为驱动是分厂家的//使用上述方法会有重复性的操作//所以推荐使用以下方法Class.forName("com.mysql.jdbc.Driver");//上述方法会得到com.mysql.jdbc.Driver类的一个类的对象//首先它会将这个类加载到内存中//当这个类加载进内存后//这个类的静态代码块就会跟着执行//所以在静态代码块中,就已经成功注册了驱动的代码

二:建立与数据库的连接,获得连接对象

//方法一: Connection conn = DriverManager.getConnection(                "jdbc:mysql://localhost:3306/jdbc",                "root",                "111111"        ); //方法二:   Connection conn = DriverManager.getConnection(        "jdbc:mysql://localhost:3306/jdbc?   user=root&password=111111");  //? 起到的作用是连接参数  //user是参数名,root是参数值(数据库用户名)  //&是与,在参数与参数之间起到连接作用 //方法三:  Connection conn = DriverManager.getConnection(           "jdbc:mysql://localhost:3306/jdbc",properties        );//创建一个properties对象//用来存储参数,用户名密码Properties properties = new Properties();//以key-value的方式存储properties.setProperty("user","root");properties.setProperty("password","111111");      

三:根据连接对象,获得一个对象

//方法一:根据连接对象,获得statement对象Statement statement = conn.createStatement();//上述方法存在SQL注入漏洞所以并不推荐使用//推荐方法如下//方法二://查询表stu中张益达的所有信息//获得预处理对象PreparedStatement pstmt = conn.prepareStatement         //?只为一个占位符         ("select * from stu where name = ?;");         // 1 为第一个?号的位置         //假如想往第二个问号里添加参数那么就写2         //假如要使用增删改功能,那么在values后面括号中         //是否有null或是否有具体的值无关         //在sql语句中有几个问号,那么就需要传递多少个参数         pstmt.setString(1,"张益达");         //执行语句并把它传入rs中         //查询使用executeQuery         //增删改使用executeUpdate         ResultSet rs = pstmt.executeQuery();         //遍历循环输出rs中的内容          while (rs.next()){            System.out.println(                    "id:"+rs.getObject(1)+"\n"+                    "名字:"+rs.getObject(2)+"\n"+                    "年龄:"+rs.getObject(3)            );        }## 四:根据获得的对象执行SQL语句 ##

//由获取到statement对象,执行sql语句
statement.execute(“你需要执行的sql语句”)
//同理
//查询使用executeQuery
//增删改使用executeUpdate
//在使用executeQuery与executeUpdate他们的返回值为受影响 的行数即为int类型
int a = statement.executeQuery(“你需要执行的sql语句”);
//如果使用execute则是布尔类型
//即执行sql语句后,得到了一个ResultSet对象就会返回true
//如果得到的是受影响的行数,或者没有得到什么结果,那么返回 false;
//得出的结果一般使用xx.next进行while循环遍历输出

## 五:释放资源(关流) ##释放资源即流即使用try catch finally进行关流

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//建立集合接收结果并遍历输出
List stus = new ArrayList<>();
try {
Class.forName(“com.mysql.jdbc.Driver”);

         conn = DriverManager.getConnection                   ("jdbc:mysql://localhost:3306/jdbc?user=root&password=111111");

// jdbc: mysql://localhost: 3306 /jdbc ? 参数
// 协议 子协议 本机地址 端口号 数据库名字

         stmt = conn.createStatement();        //执行查询语句         rs = stmt.executeQuery                ("SELECT * FROM stu;");        //判断下一行有没有数据        //如果有数据,会返回true,没有数据的话就返回false        //true就循环,false就停止        while (rs.next()){            //创建stu对象,并将数据set进stu对象中            Stu stu = new Stu();            stu.setId(rs.getInt(1));            stu.setName(rs.getString(2));            stu.setAge(rs.getInt(3));            //添加到集合里            stus.add(stu);        }        for (Stu stu:stus){            //输出一下            System.out.println(stu.toString());        }    } catch (ClassNotFoundException e) {        e.printStackTrace();    } catch (SQLException e) {        e.printStackTrace();    } finally {//      释放资源       if (conn!=null){           try {               conn.close();           } catch (SQLException e) {               e.printStackTrace();           }       }        if (stmt!=null){            try {                stmt.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        if (rs!=null){            try {                rs.close();            } catch (SQLException e) {                e.printStackTrace();            }        }    }}

}

在上述代码中使用了javaBean即建一个类封装一个方法进去使用javaBean有两个注意事项1:javaBean中,一定要有一个空参数的构造方法2:javaBean中的属性,可以不是成员变量,但是属性名一定要与表中的字段名一致## JdbcUtil ##使用JdbcUtil会帮助我们更便捷的注册使用Jdbc先建立一个配置文件Jdbcfg.properties来存储我们的驱动,地址与用户密码,更改只需在配置文件更改即可

//驱动类的路径
private static String driverClass=null;
//连接数据库使用的url
private static String url = null;
//用户名和密码
private static String user = null;
private static String password = null;
private static Connection conn =null;
static {
try {
ClassLoader cl = JdbcUtil.class.getClassLoader();
InputStream stream = cl.getResourceAsStream(“jdbcfg.properties”);
//得到流中的数据
//创建一个Properties对象
Properties prop = new Properties();
//通过Properties对象的load方法,加载流中的数据
prop.load(stream);
//根据key,获得value
driverClass = prop.getProperty(“driverClass”);
url = prop.getProperty(“url”);
user = prop.getProperty(“user”);
password = prop.getProperty(“password”);
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

//写一个静态方法,获取连接对象public static Connection getConnection() throws SQLException {    return DriverManager.getConnection(url,user,password);}//写一个静态方法,获得stmt对象

public static Statement getStatement() throws SQLException {
conn = getConnection();
return conn.createStatement();
}
public static void release(){
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void release( Statement stmt){
release(stmt,null);

}//写一个静态方法,来释放资源//如果想要释放Connection对象,需要调用Connection对象的close方法//所以需要将Connection对象传入到release方法中//然后再release方法中调用该对象的close方法//释放资源//statement对象与ResultSet对象同理public static void release( Statement stmt, ResultSet rs){    release();    if (stmt!=null){        try {            stmt.close();        } catch (SQLException e) {            e.printStackTrace();        }    }    if (rs!=null){        try {            rs.close();        } catch (SQLException e) {            e.printStackTrace();        }    }}
配置文件为:driverClass=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/cuser=rootpassword=111111使用时只需 Connection conn = JdbcUtil.getConnection();即可## 批处理 ## 需要向数据库发送多条sql语句时, 为了提升执行效率, 可以考虑采用JDBC的批处理机制.

Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement
(“INSERT INTO stu VALUES (?,?,?);”);
pstmt.setInt(1,8);
pstmt.setString(2,”僚机”);
pstmt.setInt(3,20);
//通过这个方法可以实现批处理操作
//调用这个方法后,会将这个sql先存起来,等待执行
pstmt.addBatch();

    pstmt.setInt(1,9);    pstmt.setString(2,"机长");    pstmt.setInt(3,25);    //又存了一条等待执行    pstmt.addBatch();    //执行批处理中存着的sql语句    //批处理中各个sql语句之间执行成功或失败是无联系的    //即使第一条语句会出现主键重复的错误    //也不会影响第二条语句将数据插入到数据库中    //因此推荐使用事物操作    pstmt.executeBatch();
## 事物 ##对数据的修改要么全部执行 要么全部不执行事物的编写需要在try  catch 中进行

Connection conn =null;
try {
conn = JdbcUtil.getConnection();
//设置提交方式为手动提交
//开启事物
conn.setAutoCommit(false);
//创建一个预处理对象
PreparedStatement pstmt = conn.prepareStatement
(“UPDATE 表名 SET m=? WHERE name=?;”);

        pstmt.setInt(1,700);        pstmt.setString(2,"张大炮");        pstmt.executeUpdate();        pstmt.setInt(1,1300);        pstmt.setString(2,"张益达");        pstmt.executeUpdate();        //操作无异常,提交事务        conn.commit();    } catch (Exception e) {        //回滚到事物开始之前状态        try {         //操作出现异常,撤销事务:            conn.rollback();            System.out.println("回滚了");        } catch (SQLException e1) {            e1.printStackTrace();        }    }

“`

DbUtils

DbUtils是Apache提供的一个开源的
方便我们操作的jdbc的jar包
QuerRunner类,是该jar包的核心类
所有的操作数据库的方法都被封装在这个类中更新,
查询都是使用QueryRunner类

原创粉丝点击