什么是JDBC?
JDBC是Java数据库连接(Java DataBase Connectivity)技术的简称,提供连接各种常用数据库的能力!
1.方式一(配置文件实现):
<!-- 1. 连接池实例 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hib_demo"></property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="6"></property> </bean>
2.方式二(java代码实现):
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException, IllegalAccessException { Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");// 加载驱动 Connection conn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs", "sa", "root");// 获取连接 Statement sts = conn.createStatement();// 创建一个 Statement 对象来将 SQL 语句发送到数据库 ResultSet set = sts.executeQuery("select * from t_user order by age_");// 执行sql System.out.println(" |用户id |姓名 |年龄 |出生日期 |email |"); while (set.next()) {// 得到结果并输出到网页 System.out.print(" |"); System.out.print(set.getInt("id_") + " |"); System.out.print(set.getString("name_") + " |"); System.out.print(set.getInt("age_") + " |"); System.out.print(set.getDate("birth_") + " |"); System.out.print(set.getString("email_") + " |"); System.out.println(); } }