使用mysql(6部曲)

 

使用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     }

最后 使用预编译语句可防止SQL语句的注入问题,preparestatment

1 String sql = "select * from user where username=?and password =?";
2 ps = conn.prepareStatement(sql);
3 ps.setString(1, username);
4 ps.setString(2, password);
5 rs = ps.executeQuery();

 

转载于:https://www.cnblogs.com/dyyz1993/p/4100144.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值