定义:JDBC是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
#1. 连接数据库
注意要先导入mysql连接的驱动包
下面还有另以一种连接方式:利用驱动管理器类连接数据库[推荐]
原因如下:
我们继续,添加完代码,查找一下学生表的人数吧
我们可以抽取出反复重用的代码:
package cn.proj_jdbc.utils;
import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties;
import com.mysql.jdbc.Statement;
public class JdbcUtil { /** * 连接数据库数据 */ private static String url=null; private static String user=null; private static String password=null; private static String driverClass=null; /** * 单例模式 ,防止被创建 */ private JdbcUtil(){}
/** * 注册驱动程序 */ static{ try { // 读取db.properties文件 FileInputStream inStream=new FileInputStream("./resources/db.properties"); // 加载文件 Properties properties=new Properties(); properties.load(inStream); // 读取信息 url=properties.getProperty("url"); user=properties.getProperty("user"); password=properties.getProperty("password"); driverClass=properties.getProperty("driverClass"); // 注册驱动 Class.forName(driverClass); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } /** * 获取连接对象 * @throws SQLException */ public static Connection getConnection() throws SQLException{ System.out.println(url); return DriverManager.getConnection(url,user,password); }
/** * 关闭连接对象 * @throws SQLException */ public static void Close(Connection conn,Statement statement) throws SQLException{ if(statement!=null){ statement.close(); } if(statement!=null){ conn.close(); } }
public static void Close(Connection conn,PreparedStatement statement,ResultSet resultSet) throws SQLException{ if(resultSet!=null){ resultSet.close(); } if(statement!=null){ statement.close(); } if(statement!=null){ conn.close(); } } } |
同时我们还可以把数据库配置的数据添加到db.properties
db.properties文件: url=jdbc:mysql://localhost:3306/schooldb user=root password=root driverClass=com.mysql.jdbc.Driver
|