MySQL学习(三)——Java连接MySQL数据库
时间:2021-07-01 10:21:17
帮助过:34人阅读
package cn.itheima.test;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9
10 import org.junit.Test;
11
12 public class TestLogin {
13 @Test
14 public void testLogin(){
15 try {
16 login1("zhangsan","999"
);
17 }
catch (Exception e) {
18 e.printStackTrace();
19 }
20 }
21 public void login1(String username,String password)
throws ClassNotFoundException, SQLException{
22 /*
23 * 用户登录方法
24 */
25 //1.注册驱动
26 Class.forName("com.mysql.jdbc.Driver"
);
27 //2.获取连接
28 Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/web08","root","12345"
);
29 //3.编写sql语句
30 String sql="select * from tbl_user where uname=? and upassword=?"
;
31 //4.创建预处理对象
32 PreparedStatement pstmt=
conn.prepareStatement(sql);
33 //5.设置参数(给占位符)
34 pstmt.setString(1
, username);
35 pstmt.setString(2
, password);
36 //6.执行查询操作
37 ResultSet rs=
pstmt.executeQuery();
38 //7.对结果集进行处理
39 if(rs.next()){
40 System.out.println("恭喜您,"+username+"登录成功!"
);
41 }
else{
42 System.out.println("账号或密码错误!"
);
43 }
44 if(rs!=
null) rs.close();
45 if(pstmt!=
null) pstmt.close();
46 if(conn!=
null) conn.close();
47 }
48 }
右击Run As->JUnit Test,执行结果为:恭喜您,zhangsan登录成功!
MySQL学习(三)——Java连接MySQL数据库
标签:jdb row throws 测试的 ring 控制台 trace junit except