1,在根目录创建 mysql.properties 文件,使用这个文件是为了方便以后生成class文件后可修改链接任意数据库
2,导入jar包,自行百度下载。
3,写一个 SqlUtil.class (Sql工具类)
package com.sogood.util; import java.io.IOException; import java.sql.*; import java.util.Properties; public class SqlUtil { private static String username; private static String password; private static String url; static { Properties pps = new Properties(); try { pps.load(SqlUtil.class.getResourceAsStream("/com/sogood/mysql.properties")); username = pps.getProperty("username"); password = pps.getProperty("password"); url = pps.getProperty("url"); } catch (IOException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, username, password);// 创建数据连接 } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } catch (ClassNotFoundException e) { throw new RuntimeException("驱动类找不到"); } return con; } public static void close(Connection con, Statement stm, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stm != null) { try { stm.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
4,写一个Demo.class 类测试一下
1 package com.sogood.jdbc; 2 3 import com.sogood.util.SqlUtil; 4 5 import java.sql.Connection; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 10 public class Demo { 11 public static void main(String[] args) throws SQLException { 12 query(); 13 } 14 15 private static void query() { 16 Connection con = null; 17 Statement stm = null; 18 ResultSet rs = null; 19 try { 20 con = SqlUtil.getConnection(); 21 String sql = "SELECT * FROM STUDENT"; 22 stm = con.createStatement(); 23 rs = stm.executeQuery(sql); 24 System.out.println("查询结果:"); 25 while (rs.next()) { 26 int id = rs.getInt("id"); 27 System.out.println("id = " + id); 28 } 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } finally { 32 SqlUtil.close(con, stm, rs); 33 } 34 } 35 }
时间: 2024-11-09 08:04:19