JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。JDBC只向各大数据库产商提供统一的驱动接口,具体的实现由各大产商实现,每个数据库产商有不同的实现,但是我们可以利用多态,实现面向接口编程,而不用管数据库产商的具体实现细节。在Java程序中使用具体数据库时,需要先引入对应的jar包。比如mysql对应的mysql-connector-java-5.1.13-bin.jar,如果是oracle等数据库需要引入其他的jar包。
JDBC建立连接(MySQL)
在类路径下建立properties文件,在工具类JDBCTools中加载该文件
在jdbc.properties文件中:
1 driverClass = com.mysql.jdbc.Driver //这一句代表数据库驱动类的全类名
2 jdbcUrl = jdbc:mysql://localhost:3306/test //这一句是配置需要访问的数据库,test是数据库名
3 user = root
4 password = 123
建立数据库连接和关闭连接的工具类jdbcTools
1 public class jdbcTools {
2
3 //获取数据库连接
4 public static Connection getConnection() throws Exception {
5 Connection connection = null;
6 String driverClass = null;
7 String url = null;
8 String user = null;
9 String password = null;
10
11 InputStream in = jdbcTools.class.getClassLoader().getResourceAsStream("jdbc.properties");//加载配置文件
12 Properties properties = new Properties();
13 properties.load(in);
14
15 driverClass = properties.getProperty("driverClass");
16 url = properties.getProperty("jdbcUrl");
17 user = properties.getProperty("user");
18 password = properties.getProperty("password");
19
20 Class.forName(driverClass);//通过全类名加载驱动类
21 connection = DriverManager.getConnection(url,user,password);//DriverManager可以实现对各个数据库驱动类的同一管理,并获取数据库的连接
22
23 return connection;
24
25 }
26
27 //关闭资源
28 public static void releaseResource(Statement statement,Connection connection){
29 if(statement != null){
30 try{
31 statement.close();
32 }catch (Exception e){
33 e.printStackTrace();
34 }
35 }
36 if(connection != null){
37 try{
38 connection.close();
39 }catch (Exception e1){
40 e1.printStackTrace();
41 }
42 }
43 }
44
45 public static void releaseResource(ResultSet resultSet,Statement statement, Connection connection){
46
47 if(resultSet != null){
48 try{
49 resultSet.close();
50 }catch (Exception e){
51 e.printStackTrace();
52 }
53 }
54 if(statement != null){
55 try{
56 statement.close();
57 }catch (Exception e){
58 e.printStackTrace();
59 }
60 }
61 if(connection != null){
62 try{
63 connection.close();
64 }catch (Exception e1){
65 e1.printStackTrace();
66 }
67 }
68 }