JDBC简介
JDBC就是java 数据库连接,是java中的API,我们将用它来执行SQL语句,除了我们平常的mysql数据库以外,jdbc还提供了统一的多种的数据库。
JDBC连接数据库步骤
1,在项目的src下创建一个properties的文本的根目录
并在properties文本中写入URL,user,password,driverclass
2 :获取一个类加载器然后调用getResourceAsStream方法,返回的是一个inputstream对象,在new出一个Properties(存储键值对)对象,在调用properties的load方法
InputStream is= TestConnection.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(is);
3:调用Properties的getProperty方法,得到user,password URL ,driverclass
String user= properties.getProperty("user");
String password= properties.getProperty("password");
String url= properties.getProperty("url");
String driverclass= properties.getProperty("driverclass")
4:采用反射,反射出Driver,Driver类中有一个静态方法去注册驱动,所有我们就可以不用自己去注册驱动
Class.forName(driverclass);
5.获取连接,调用DriverManager的getConnection方法,返回一个Connection对象
Connection con=DriverManager.getConnection(url,user,password);
6.最后完整的代码:
InputStream is= TestConnection.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(is);
String user=properties.getProperty("user");
String passward=properties.getProperty("passward");
String url=properties.getProperty("url");
String driverclass=properties.getProperty("driverclass");
Class.forName(driverclass);
Connection connection= DriverManager.getConnection(url,user,passward);