意志、工作和等待是成功的金字塔的基石。
 Will, work and wait are the pyramidal cornerstones for success.
文章目录
- JDBC简介:
 - JDBC访问数据库步骤
 - Statement
 - PreparedStatement
 
JDBC简介:
在Java应用程序中,JDBC(Java Database Connectivity)是一种用于与数据库建立连接并执行SQL操作的标准接口。通过JDBC,您可以轻松地与各种关系型数据库进行交互,例如MySQL、PostgreSQL、Oracle等。
 
JDBC访问数据库步骤
直接上代码:
    //初始化
    Connection conn = null;//连接对象
    Statement statement = null;  //执行sql的对象
    ResultSet rs = null; //结果集
    int result=0;//返回结果
//   开始连接数据库
//   1.加载驱动 com.mysql.jdbc.Driver
    Class.forName("com.mysql.jdbc.Driver");
//   2.连接数据库
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shooltest?useUnicode=true&characterEncoding=utf-8","root","root");
//   3.编写要执行的sql语句
    String sql = "select count(*) from student where StudentName='"+name+"' and LoginPwd='"+pwd+"'";
//   4.创建执行SQL语句的statement对象
    Statement statement1 = conn.createStatement();
//   5.开始执行
    //如果是查询select: statement.execQuery(sql);  ---有结果集
    //如果是增删改 insert delete update: statement.executeUpdate(sql); ---没有结果集
    ResultSet execute = statement1.executeQuery(sql);
    //6.处理结果集
    if(execute.next()){
        result = execute.getInt("count(*)");//已知count(*)的类型是整数用getInt,如果不知道可以用getObject
        out.print(execute.getInt("count(*)"));
    }
    if(result==1){
        session.setAttribute("loginuser",name);
        response.sendRedirect("index.jsp");
    }else {
        out.print("<script>alert('用户名或密码错误');location.href='login.jsp';</script>");
    }
 
当你在JavaServer Pages(JSP)中使用数据库时,通常会涉及到使用Statement和PreparedStatement来执行SQL查询语句。下面是关于这两者的简要介绍:
Statement
-  
描述: Statement是Java中的一个接口,用于执行静态SQL语句并返回它所生成的结果。它用于执行不带参数的简单SQL语句。
 -  
特点:
- Statement执行SQL语句时,每次都会将SQL语句发送到数据库执行,适用于执行不需要参数化的SQL语句。
 - Statement存在SQL注入的风险,因为它直接将用户输入的数据拼接到SQL语句中,可能导致安全问题。
 
 -  
示例代码:
Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); 
PreparedStatement
-  
描述: PreparedStatement也是用于执行SQL语句的接口,它继承自Statement。PreparedStatement对象表示预编译的SQL语句,可以通过占位符(?)来设置参数,提高执行效率并防止SQL注入攻击。
 -  
特点:
- PreparedStatement预编译SQL语句,可以多次执行,提高了执行效率。
 - 使用PreparedStatement可以有效防止SQL注入攻击,因为参数值会被安全地处理。
 
 -  
示例代码:
Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?"); pstmt.setString(1, "john_doe"); ResultSet rs = pstmt.executeQuery(); 
在JSP中,通常推荐使用PreparedStatement来执行SQL查询,以提高执行效率并增加安全性。通过简单的参数设置,PreparedStatement可以更好地防止SQL注入攻击,同时也更加灵活和高效。
这只是一个简要介绍,你可以根据需要进一步了解这两种方式的更多细节和用法。希望这个简要介绍对你有所帮助!如果有任何问题或需要进一步解释,请随时告诉我。










![[数据结构]OJ用队列实现栈](https://img-blog.csdnimg.cn/direct/50815f643af44304ad9d7070ccf6f523.png)
![[Spring] IoC 控制反转和DI依赖注入和Spring中的实现以及常见面试题](https://img-blog.csdnimg.cn/direct/593357fb2524418faa30e4f07364f3a7.png)







