黑马程序员技术交流社区

标题: Question and Resolve After Learning Java for the 4th Week [打印本页]

作者: REVEBAMBOU    时间: 2019-4-17 18:19
标题: Question and Resolve After Learning Java for the 4th Week
This week I almost learnt MySQL. This is a language is different from Java but there are some relationships between them. For example, java language can access MySQL with using the DataSource interface in Java. Actually, this is a simple way to connect to MySQL database. And there is some disadvantage with this way. Every time connecting MySQL database, java needs apply for Connection resource with registration, which will be using a lot of source of the internal memory. In order to solve this issue, numerous Connection Pools had been offered, such as c3p0, druid and as on.
Connect MySQL with the simplest way:
1.          Class.forName(path);
2.        Connection conn = ManagerDriver().getConnection();
3.        PreparedStatement ps = conn.prapareStatement();
4.        String sql = “select * from stu”;
5.        ResultSet rs = ps.exeuteQuery(sql);
6.        While(rs.next()){
7.        String field = rs.getString(“field”)
8.        Sout(field)
9.        Rs.close; ps.close(); conn.close();
Create a JdbcUtils class:
1.        Use Properties to get fields.
2.        Define a getConnection method;
3.        Define a getDataSource method;
4.        Define a close method;

Connect MySQL database with using the JbdcUtils class:
1.        Get Connection source with the JdbcUtils class.
2.        Get PreparedStatedment source with the prepareStatement method of Connection
3.        Define a sql string.
4.        Set the values of the string with PreparedStatement.
5.        Execute the sql string.
6.        Handle the result (Query or others oprations)
Connection MySQL database with via Druid pool.
1.        Re-write the JdbcUtils class.
2.        Get the properties in the Static code
3.        Use Duird method to get the DataSource.
4.        Create the getConnection and getDataSource method
5.        Create the close method.
6.        Get the Preparedstatement source with the Connection
7.        Execute sql string after defined and setting the values.
8.        Hand the result.
Connection MySQL database with the JdbcTemplate template (need to get DataSource with the 2nd JdbcUtils class.)
1.        Get the DataSource via the JdbcUtils.
2.        Create a template object with the DataSource
3.        Execute SQL string with correct format, such as
template.execute(sql,values, value2…);
template.QueryForMap(sql,value1, value2..);
template.QueryForList(sql, value1,value2..)
4.        Handle the result.





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2