代码如下:
package DatabaseConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.commons.dbcp2.BasicDataSource;
public class practice06 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//1.创建BasicDataSource对象
BasicDataSource datasource = new BasicDataSource();
//2.设置四个基本的选项,主要是为了连接数据库
datasource.setDriverClassName("com.mysql.jdbc.Driver");
datasource.setUrl("jdbc:mysql://localhost:3306/student_information");
datasource.setUsername("root");
datasource.setPassword("1234");
//3.获取数据库连接
Connection conn = datasource.getConnection();
//System.out.println(conn);
//4.准备sql语句
String sql = "select *from student";
//5.预编译
PreparedStatement ptmt = conn.prepareStatement(sql);
//6.执行sql语句
ResultSet rs = ptmt.executeQuery();
//7.处理结果
while(rs.next()) {
System.out.println(rs.getString("Sno") + "\t" + rs.getString("Sname") + "\t" + rs.getString("Ssex") + "\t"
+ rs.getInt("Sage") + "\t" + rs.getString("Sdept") + "\t" + rs.getString("S_entrance"));
}
//8.释放资源
rs.close();
ptmt.close();
conn.close();
datasource.close();
}
}