JdbcUtils 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 COPY package com.dwx.jabcstudy;import java.io.InputStream;import java.sql.*;import java.util.Properties;public class JdbcUtils { private static String driver = null ; private static String url = null ; private static String username = null ; private static String password = null ; static { try { InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties" ); Properties properties = new Properties(); properties.load(in); driver = properties.getProperty("driver" ); url = properties.getProperty("url" ); username = properties.getProperty("username" ); password = properties.getProperty("password" ); Class.forName(driver); }catch (Exception e){ System.out.println("出错了!!!" ); }finally { } } public static Connection getConnection () throws Exception { return DriverManager.getConnection(url, username, password); } public static void release (Connection connection, Statement statement, ResultSet resultSet) throws SQLException { if (resultSet!=null ){ try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (statement!=null ){ statement.close(); } if (connection!=null ){ connection.close(); } } }
注意:这个JdbcUtils工具类需要放在调用它的类的同一个包下
db.properties 1 2 3 4 5 COPY driver =com.mysql.cj.jdbc.Driver url =jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEnconding=utf8&useSSL=true username =dwx password =123456
注意:这个配置需要放在src目录下
操作实例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 COPY package com.dwx.jabcstudy;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCSecond { public static void main (String[] args) throws Exception { Connection connection = null ; Statement statement = null ; ResultSet resultSet = null ; try { connection = JdbcUtils.getConnection(); statement = connection.createStatement(); String sql = "INSERT INTO dwx(id,`name`,`sex`)" + "VALUES(6,'kti','m')" ; int i = statement.executeUpdate(sql); if (i>0 ){ System.out.println("插入成功!!!" ); } } catch (Exception e) { e.printStackTrace(); }finally { JdbcUtils.release(connection,statement,resultSet); } } }