JDBC学习笔记(二)
连接管理
将连接数据库的基本信息写在db.properties文件中
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。1 # db.properties 2 jdbc.driver=com.mysql.cj.jdbc.Driver 3 jdbc.url=jdbc:mysql://127.0.0.1:3306/student?characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false 4 jdbc.username=root 5 jdbc.password=LT199541
将数据库连接操作封装到一个DBUtils类中方便直接调用方法创建连接:
1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.SQLException; 8 import java.util.Properties; 9 10 import javax.imageio.IIOException; 11 12 public class DBUtils { 13 14 static String driver; 15 static String url; 16 static String username; 17 static String password; 18 19 /* 20 * 初始化静态属性 21 * 22 */ 23 static { 24 try { 25 Properties cfg = new Properties(); 26 InputStream in = DBUtils.class.getClassLoader().getResourceAsStream("db.properties"); 27 cfg.load(in); 28 driver = cfg.getProperty("jdbc.driver"); 29 url = cfg.getProperty("jdbc.url"); 30 username = cfg.getProperty("jdbc.username"); 31 password = cfg.getProperty("jdbc.password"); 32 } catch (Exception e) { 33 e.printStackTrace(); 34 throw new RuntimeException(); 35 } 36 37 } 38 39 /* 40 * 封装创建数据库连接的过程 简化数据库连接 41 */ 42 public static Connection getConnection() throws ClassNotFoundException, SQLException { 43 44 /* 注册驱动并建立连接 */ 45 Class.forName(driver); 46 Connection coon = DriverManager.getConnection(url, username, password); 47 return coon; 48 } 49 50 /* 51 * 封装关闭数据库连接的方法 52 * 53 */ 54 public static void close(Connection coon) { 55 if (coon != null) { 56 try { 57 coon.close(); 58 } catch (Exception e) { 59 e.printStackTrace(); 60 } 61 } 62 } 63 }
标准的数据库查询代码:
import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /* * 标准连接数据库写法 * */ public class Demo3 { public static void main(String[] args) { Connection coon = null; try { coon = DBUtils.getConnection(); Statement st = coon.createStatement(); String sql = "select * from robin_demo"; ResultSet rs = st.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String gender = rs.getString("gender"); } rs.close(); //释放查询结果 st.close(); //释放语句对象 } catch (Exception e) { e.printStackTrace(); } finally { DBUtils.close(coon); } } }

更多精彩