当前位置:Gxlcms > 数据库问题 > JDBC

JDBC

时间:2021-07-01 10:21:17 帮助过:3人阅读

static void main(String[] args) throws Exception{ Class.forName("com.mysql.jdbc.Driver"); //获取连接 String url = "jdbc:mysql://localhost:3306/mybase"; String username = "root"; String password = "123"; java.sql.Connection con = DriverManager.getConnection(url, username,password); //编写sql语句 String sql = "UPDATE sort SET sname=?,sprice=? WHERE sid=?"; //获取执行平台 PreparedStatement pst = con.prepareStatement(sql); //执行修改内容 pst.setString(1, "汽车美容"); pst.setObject(2, 48888); pst.setObject(3, 1); //执行程序 pst.executeUpdate(); //释放资源 pst.close(); con.close(); }

 

三、 sql注入:
  注入攻击:SELECT * FROM 用户表 WHERE NAME = ‘XXX’ AND PASSWORD =’ XXX’  OR ’a’=’a’;
  防止注入攻击:将Statement改为PreparedStatement
   【PerparedStatement pst = con.prepareStatement(sql);】
   
 预处理对象:
  Preparement pst = con.prepareStatement(sql);
  
 
 四、封装JDBC工具类
  创建静态连接方法:返回Connection
  创建静态关闭方法:无返回

//JDBCUtils工具类代码
            public class JDBCUtils {
          //无参构造方法
private JDBCUtils(){}
          //定义静态私有的变量
private static Connection con ; //静态代码块连接数据库 static{ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mybase"; String username="root"; String password="123"; con = DriverManager.getConnection(url, username, password); }catch(Exception ex){ throw new RuntimeException(ex+"数据库连接失败"); } } /* * 定义静态方法,返回数据库的连接对象 */ public static Connection getConnection(){ return con; } //关闭资源的静态方法,方便调用 public static void close(Connection con,Statement stat){ if(stat!=null){ try{ stat.close(); }catch(SQLException ex){} } if(con!=null){ try{ con.close(); }catch(SQLException ex){} } } //关闭资源的静态方法,方便调用 public static void close(Connection con,Statement stat , ResultSet rs){ if(rs!=null){ try{ rs.close(); }catch(SQLException ex){} } if(stat!=null){ try{ stat.close(); }catch(SQLException ex){} } if(con!=null){ try{ con.close(); }catch(SQLException ex){} } } } //测试JDBCUtils工具类的代码 public class TestJDBCUtils { public static void main(String[] args)throws Exception { Connection con = JDBCUtils.getConnection(); PreparedStatement pst = con.prepareStatement("SELECT sname FROM sort"); ResultSet rs = pst.executeQuery(); while(rs.next()){ System.out.println(rs.getString("sname")); } JDBCUtils.close(con, pst, rs); } }

 


   

JDBC

标签:ble   sql   time   bool   静态代码块   面向接口   new   res   creat   

人气教程排行