您的位置:首页 > 博客中心 > 数据库 >

使用mysql(6部曲)

时间:2022-03-14 02:33

 

使用properties文件配置数据库驱动,uri,用户名和密码;以便于日后更换数据库不用更改源代码;

driver=com.mysql.jdbc.Driver
uri=jdbc:mysql://localhost:3306/day10
user=root
password=root

 

1.注册驱动

1 public static Connection getConn() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
2         
3         Class.forName(prop.getProperty("driver"));
4         return DriverManager.getConnection(prop.getProperty("uri"),prop.getProperty("user"),prop.getProperty("password"));
5         
6         
7     }

 

2.创建连接器

Connection conn = JDBCUtils.getConn();
//Connection conn = DriverMananger("uri,user,password");

 

3.获取传输器

Statment stat = conn.createStatement();

 

5.利用传输器查询语句,并返回结果集

stat.executeUpdate(sql); 增删改

stat.executeQuery(sql);查询语句

6.关闭资源

 1 public static void close(Connection conn,Statement stat,ResultSet rs){
 2         
 3             if(rs!=null){
 4                 try {
 5                     rs.close();
 6                 } catch (SQLException e) {
 7                     throw new RuntimeException(e);
 8                     
 9                 }finally{
10                     rs=null;
11                 }
12             }
13             if(stat!=null){
14                 try {
15                     stat.close();
16                 } catch (SQLException e) {
17                     throw new RuntimeException(e);
18                     
19                 }finally{
20                     stat=null;
21                 }
22             }
23             if(conn!=null){
24                 try {
25                     conn.close();
26                 } catch (SQLException e) {
27                     throw new RuntimeException(e);
28                     
29                 }finally{
30                     conn=null;
31                 }
32             }
33     }

 

热门排行

今日推荐

热门手游