企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
![](https://box.kancloud.cn/24b8a064538438026bbaa7ec629d84b2_511x359.png) ![](https://box.kancloud.cn/9b1de84dcc6cd7748fc1e101ec95af47_500x285.png) ![](https://box.kancloud.cn/51e462e3194ccf021da2908bfd6aeefb_522x190.png) ![](https://box.kancloud.cn/392fc8d98ab083ae1f8085293af3c390_520x327.png) Login.java ~~~ package zyw.crud; import java.sql.*; public class Login { public void login(String name,String pass) throws SQLException, ClassNotFoundException { // 1、注册数据库的驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取数据库连接 String url="jdbc:mysql://122.14.200.136:3306/javadb"; Connection connection = DriverManager.getConnection(url, "root", "6a133f0024"); //3.获取操作数据库的对象 Statement statement= connection.createStatement(); String sql = "select * from user WHERE name='"+name+"'AND pass='"+pass+"'"; ResultSet resultSet=statement.executeQuery(sql); //4.遍历结果集,取出数据 if (resultSet.next()){ String name1=resultSet.getString("nickname"); System.out.println(name1+"登录成功" ); }else{ System.out.println("登陆失败"); } //5.关闭对象 resultSet.close(); statement.close(); connection.close(); } public void login1(String name,String pass) throws SQLException, ClassNotFoundException { // 1、注册数据库的驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取数据库连接 String url="jdbc:mysql://122.14.200.136:3306/javadb"; Connection connection = DriverManager.getConnection(url, "root", "6a133f0024"); //3.获取操作数据库的对象 //Statement statement= connection.createStatement(); //String sql = "select * from user WHERE name='"+name+"'AND pass='"+pass+"'"; String sql="select * from user WHERE name=? AND pass=?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); //ResultSet resultSet=statement.executeQuery(sql); preparedStatement.setString(1,name); preparedStatement.setString(2,pass); ResultSet resultSet = preparedStatement.executeQuery(); //4.遍历结果集,取出数据 if (resultSet.next()){ String name1=resultSet.getString("nickname"); System.out.println(name1+"登录成功" ); }else{ System.out.println("登陆失败"); } //5.关闭对象 resultSet.close(); //statement.close(); preparedStatement.close(); connection.close(); } } ~~~ 单元测试LoginTest.java ~~~ package zyw.crud; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.sql.SQLException; import static org.junit.Assert.*; public class LoginTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void login() throws SQLException, ClassNotFoundException { Login login=new Login(); // login.login("xm","123"); //login.login("a' or 'a'='a","a' or 'a'='a");//a' or 'a'='a login.login1("a' or 'a'='a","a' or 'a'='a"); // login.login1("xm","123"); } } ~~~