A. 導入所需的jar包java
import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException;
B. 獲取與數據庫的鏈接mysql
private static Connection getConn() { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/samp_db"; String username = "root"; String password = ""; Connection conn = null; try { Class.forName(driver); //classLoader,加載對應驅動 conn = (Connection) DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; }
C.拿着鏈接cnn去操做數據庫獲取PreparedStatementspring
private static Integer getAll() { Connection conn = getConn(); String sql = "select * from students"; PreparedStatement pstmt; try { pstmt = (PreparedStatement)conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); int col = rs.getMetaData().getColumnCount(); System.out.println("============================"); while (rs.next()) { for (int i = 1; i <= col; i++) { System.out.print(rs.getString(i) + "\t"); if ((i == 2) && (rs.getString(i).length() < 8)) { System.out.print("\t"); } } System.out.println(""); } System.out.println("============================"); } catch (SQLException e) { e.printStackTrace(); } return null; }
A. 配置數據源<bean>-applicationcontext.xmlsql
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="username" value="root"></property> <property name="password" value="密碼"></property> <property name="url" value="jdbc:mysql://localhost:3306/newtest"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> </bean>
B. 配置鏈接池<bean>-applicationcontext.xml數據庫
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
C. 注入java中並使用app
@Autowired private JdbcTemplate jdbcTemplate; ..... String sql = "SELECT * FROM stu" return jdbcTemplate.queryForList(sql);
3.1 MyBatis(前身是iBatis)框架
另見博客!:https://my.oschina.net/u/3697586/blog/1924307url
3.2 Hibernatespa
3.3 JPA .net