JDBC 通过读取配置文件 链接数据库

一    准备工作

1  安装 MySQL  

2  下载JDBC所需要的包

3   安装好JDK

二   操作步骤

1  创建一个web项目,把对应的包和配置文件放在适当的位置,通常情况如下

 jdbc.properties里面的内容

Driver=com.mysql.jdbc.Driver  驱动名字 JDBC驱动: 
url
=jdbc:sqlserver://+数据库地址+;DatabaseName=数据库名字
userName=用户名
password
=密码

2 在类里面去读取jdbc.properties 的内容 以及书写  链接数据库 关闭数据库 的方法

package com.bowei.utl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtl {
    // 数据库驱动
    private static String Driver = "";
    // 数据库地址
    private static String url = "";
    // 数据库用户名
    private static String userName = "";
    // 数据库密码
    private static String password = "";
  static {
        Properties p = new Properties();
        try {
            // 通过相对路径加载文件
            String path=(Thread.currentThread().getContextClassLoader().getResource("").getFile()).substring(1);
            path=java.net.URLDecoder.decode(path,"utf-8");
            path=path.replace('/', '\'); // 将/换成  
            path=path.replace("file:", ""); //去掉file:  
            path=path.replace("classes\", ""); //去掉class   
            path+="sof/jdbc.properties";  //路径
            p.load(new FileInputStream(new File(path)));
            // 用getProperty方法通过关键字获取信息
            Driver = p.getProperty("Driver");
            url = p.getProperty("url");
            userName = p.getProperty("userName");
            password = p.getProperty("password");
          
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//get set
    public static String getDriver() {
        return Driver;
    }

    public static void setDriver(String driver) {
        Driver = driver;
    }

    public static String getUrl() {
        return url;
    }

    public static void setUrl(String url) {
        JdbcUtl.url = url;
    }

    public static String getUserName() {
        return userName;
    }

    public static void setUserName(String userName) {
        JdbcUtl.userName = userName;
    }

    public static String getPassword() {
        return password;
    }

    public static void setPassword(String password) {
        JdbcUtl.password = password;
    }
    // 获取数据库连接
    public static Connection getConn() {
        Connection conn = null;
        try {
            // 加载驱动
            Class.forName(Driver);
            // 获取数据库连接
            conn = DriverManager.getConnection(url, userName, password);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    // 关闭数据库资源
    public static void closeAll(ResultSet rs, Statement stat, Connection conn) {
        /* 分别按顺序关闭数据库的结果集资源,Statement 对象资源以及Connection 连接数据库对象 */
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

下面是增删查改的方法:(此处省略的学生类的代码,自己写)

insert

 1 private static int insert(Student student) {
 2     Connection conn=JdbcUtl.getConn();
 3       Statement st=null;
 4       ResultSet rs = null;
 5     int i = 0;
 6     String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
 7     PreparedStatement pstmt;
 8     try {
 9         pstmt = (PreparedStatement) conn.prepareStatement(sql);
10         pstmt.setString(1, student.getName());
11         pstmt.setString(2, student.getSex());
12         pstmt.setString(3, student.getAge());
13         i = pstmt.executeUpdate();
14         pstmt.close();
15     }  finally {
16             JdbcUtl.closeAll(rs, st, conn);//释放资源
17         }
18     return i;
19 }

update

 1 private static int update(Student student) {
 2Connection conn=JdbcUtl.getConn();

3 int i = 0;
4
String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
5
PreparedStatement pstmt;
6
try {
7
pstmt = (PreparedStatement) conn.prepareStatement(sql);
8
i = pstmt.executeUpdate();
9
System.out.println("resutl: " + i);

10 pstmt.close();

11 conn.close();

12 } catch (SQLException e) {

13 e.printStackTrace();

14 }

15 return i;

16 }

select

 1 private static Integer getAll() {
 2     Connection conn =JdbcUtl.getConn();
 3     String sql = "select * from students";
 4     PreparedStatement pstmt;
 5     try {
 6         pstmt = (PreparedStatement)conn.prepareStatement(sql);
 7         ResultSet rs = pstmt.executeQuery();
 8         int col = rs.getMetaData().getColumnCount();
 9         System.out.println("============================");
10         while (rs.next()) {
11             for (int i = 1; i <= col; i++) {
12                 System.out.print(rs.getString(i) + "	");
13                 if ((i == 2) && (rs.getString(i).length() < 8)) {
14                     System.out.print("	");
15                 }
16              }
17             System.out.println("");
18         }
19             System.out.println("============================");
20     } catch (SQLException e) {
21         e.printStackTrace();
22     }
23     return null;
24 }

delete

private static int delete(String name) {
    Connection conn = JdbcUtl.getConn();
    int i = 0;
    String sql = "delete from students where Name='" + name + "'";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        i = pstmt.executeUpdate();
        System.out.println("resutl: " + i);
        pstmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}
原文地址:https://www.cnblogs.com/Vziiii/p/6402343.html