一、连接数据库
要访问数据库,首先要加载数据库的驱动程序(只需要在第一次访问数据库时加载一次),然后每次访问数据库时创建一个Connection对象,接着执行数据库的SQL语句,最后在完成数据库操作后销毁前面创建的Connection对象,释放与数据库的连接。
示例在项目中创建类Conn,并创建getConnection()方法,获取与MySQL数据库的连接
public class Conn {
Connection con;//说明Connection对象
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功");
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
try {
con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false", "root", "12580");
//在URL后加上?userSSL=false可以避免控制台提示“提示警告不建议使用没有带服务器身份验证的SSL连接”的问题
System.out.println("数据库连接成功");
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
Conn c=new Conn();
c.getConnection();
}
}
说明:
加载数据库驱动之前,首先需要确定数据库驱动类是否成功加载到程序中,如果没有加载,可按以下步骤加载(MySQL的数据库驱动包为例)
- 将MySQL数据库的驱动包mysql_connection_java.5.1.47_bin.jar复制到当前项目
- 选中当前项目,单击鼠标右键,选中Build Path——Configure Build Path,在弹出来的对话框中左侧选中Java Build Path,然后选中Libraries选项卡,单击Add External JARs,在弹出来的对话框中选中加载的数据库驱动包,最后选择Apply按钮。
二、数据查询
数据查询主要通过Statement接口和ResultSet接口实现,其中,Statement接口用来执行SQL语句,ResultSet用来存储查询结果。
示例如何使用JDBC查询数据表中的数据
public class Gradation {
//连接数据库的方法
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false", "root", "12580");
return con;
}
public static void main(String[] args) {
Gradation test=new Gradation();
Connection con=null;
Statement stmt=null;
ResultSet res=null;
try {
con=test.getConnection();
stmt=con.createStatement();
res=stmt.executeQuery("select * from tb_stu");
while(res.next()) {
String id=res.getString("id");
String name=res.getString("name");
String sex=res.getString("sex");
String birthday=res.getString("birthday");
System.out.println("编号:"+id);
System.out.println("姓名:"+